在 Android-Kotlin 中,我从后端获取浮点数(例如 num = 10000000.47)
当我尝试对其进行 String.format 并将该数字添加到我的 balanceTextview 中时,它会以指数显示它(类似于 1.0E10)。
我想正常显示没有指数和 2 位小数的数字。 (没有精度损失!)
尝试使用 DecimalFormat("#.##") 但它没有帮助我。也许我做错了什么?
num = 10000000.47f
val dec = DecimalFormat("#.##")
var result = dec.format(num)
my result is: 10000000
It losts my decimal places
最佳答案
问题是您的号码类型。根据documentation :
For variables initialized with fractional numbers, the compiler infers the Double type. To explicitly specify the Float type for a value, add the suffix f or F. If such a value contains more than 6-7 decimal digits, it will be rounded.
举个例子,说明信息是如何丢失的:
val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817
如果值指定为
Double
而不是 Float
, IE。val num = 10000000.47
代替
val num = 10000000.47f
那么您的方法按预期工作,但可以缩短为:
"%.2f".format(num)
(请注意,较短的版本也会将“100”打印为“100.00”,这与您的方法不同,但可能仍然是理想的行为)
如果您收到
Float
从后端,那么信息已经在您这边丢失了。否则,您应该能够通过改进解析来解决问题。
关于android - Kotlin float ,带 2 位小数到字符串,没有精度损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60564707/