golang如何比较浮点数的大小

作者: adm 分类: go 发布时间: 2023-11-22

Golang浮点数比较和运算会出现误差。

浮点数储存至内存中时,2的-1、-2……-n次方不能精确的表示小数部分,所以再把这个数从地址中取出来进行计算就出现了偏差。

package main

import (
	"errors"
	"fmt"

	"github.com/shopspring/decimal"
)

func FloatCompare(f1, f2 interface{}) (n int, err error) {
	var f1Dec, f2Dec decimal.Decimal
	switch f1.(type) {
	case float64:
		f1Dec = decimal.NewFromFloat(f1.(float64))
		switch f2.(type) {
		case float64:
			f2Dec = decimal.NewFromFloat(f2.(float64))
		case string:
			f2Dec, err = decimal.NewFromString(f2.(string))
			if err != nil {
				return 2, err
			}
		default:
			return 2, errors.New("FloatCompare() expecting to receive float64 or string")
		}
	case string:
		f1Dec, err = decimal.NewFromString(f1.(string))
		if err != nil {
			return 2, err
		}
		switch f2.(type) {
		case float64:
			f2Dec = decimal.NewFromFloat(f2.(float64))
		case string:
			f2Dec, err = decimal.NewFromString(f2.(string))
			if err != nil {
				return 2, err
			}
		default:
			return 2, errors.New("FloatCompare() expecting to receive float64 or string")
		}
	default:
		return 2, errors.New("FloatCompare() expecting to receive float64 or string")
	}
	return f1Dec.Cmp(f2Dec), nil
}

func main() {
	a:=4.0
	b:="4"
	fmt.Println(FloatCompare(a,b))
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!