This is a created article in which the information may have evolved or changed.
We often need to compare the size of two floating-point types in programming, and here I share a piece of this code, as well as the unique charm of Go language functional programming:
import ("fmt""math")func main() {// 设置精确度为0.00001var a Accuracy = func() float64 { return 0.00001 }fmt.Println(a.Equal(0.11111222, 0.11111222233333)) //打印结果为:true}type Accuracy func() float64func (this Accuracy) Equal(a, b float64) bool {return math.Abs(a-b) < this()}func (this Accuracy) Greater(a, b float64) bool {return math.Max(a, b) == a && math.Abs(a-b) > this()}func (this Accuracy) Smaller(a, b float64) bool {return math.Max(a, b) == b && math.Abs(a-b) > this()}func (this Accuracy) GreaterOrEqual(a, b float64) bool {return math.Max(a, b) == a || math.Abs(a-b) < this()}func (this Accuracy) SmallerOrEqual(a, b float64) bool {return math.Max(a, b) == b || math.Abs(a-b) < this()}