@Test
fun float_test() {
val float = 1.123451234512345F
val expected = "1.123451234512345"
val actual = float.toString() //actual comes 1.1234512
assertThat(actual).isEqualTo(expected) //failed
}
当我将 float 1.123451234512345F 转换为 String 时,结果只有 1.1234512
这有什么原因吗?..
最佳答案
Is there any reason of this ?
您的文字
1.123451234512345
有 15 个十进制数字的 precision1。一个
float
只能表示 6 到 7 位精度。当数字转换为 float
时,更多的数字会丢失由编译器。可能的解决方案:使用
double
而不是 float
.1 - 实际上,您的文字是
1.123451234512345F
. F
后缀表示字面值是 float
,因此在计算字面值时精度会丢失。对于 double
字面意思,去掉 F
或替换为 D
.
关于java - Kotlin float -> 字符串转换问题(也是 Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59574482/