Groovy - 混淆 double 与 float

Groovy - confusion double vs float

我正在使用以下两个语句:-

double foo = 20.00
float bar = 20.00
println foo == bar

double foo = 20.01
float bar = 20.01
println foo == bar

它给出的输出为:-

true 
false

谁能知道这两种说法有什么区别?

doublefloat 值对每个值都没有精确的内部表示。唯一可以表示为两位小数点的 IEEE-754 二进制浮点数的十进制值是 0、0.25、0.5、0.75 和 1。其余的表示总是略有偏差,双精度数和浮点数之间的细微差异创建这种不平等行为。

这不仅适用于 Groovy,也适用于 Java。

例如:

double foo = 20.25
float bar = 20.25
println foo == bar

输出:

true

Groovy 浮点数没有准确地保存在内存中。这就是造成你们分歧的主要原因。

在Groovy中定义点号右侧后位数的精度可以通过以下方法签名实现:

public float trunc(int precision)
precision - the number of decimal places to keep.

更多详情请关注Class Float documentation.

使用Groovy语言时更倾向于使用BigDecimalclass作为浮点数。 从数字到字符串的转换要容易得多,并且可以选择在构造函数中定义浮点数的精度。

BigDecimal(BigInteger unscaledVal, int scale) Translates a BigInteger unscaled value and an int scale into a BigDecimal.

更多详情请关注Java BigDecimal documentation。由于 Groovy 语言基于 Java 语言。更多的BigDecimal将代表数字的精确值。

20.01的0.1部分在二进制中无限重复; 20.01 =

10100.00000010100011110101110000101000111101011100001010001111010111...

浮点数四舍五入(最接近)到 24 个有效位;双打四舍五入为 53。这使得 float

10100.0000001010001111011

和双

10100.000000101000111101011100001010001111010111000011

在十进制中,它们是

20.0100002288818359375 和

分别为 20.010000000000001563194018672220408916473388671875。

(你可以直接用我的decimal to floating-point converter看到这个)