android - Kotlin float ,带 2 位小数到字符串,没有精度损失

标签 android kotlin

在 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/

相关文章:

android - 在 Android 5.0 中通过 NFC 激活设备所有者期间无法连接 Wifi

android - 在模块(android 库)中使用改造 2.4.0 时出现 NoClassDefFoundError

java - 不幸的是 MyApp 已停止。我该如何解决这个问题?

android - CardView 内的 ImageView CardView 内

Android ViewGroup : what should I do in the onLayout() override?

android - Jetpack Compose 项目在我向其添加匿名类后未构建

Kotlin:将运算符作为函数参数传递

spring - 构造函数只接受引用实体的 ID,但 getter 返回实体本身 - 可能吗?

sqlite - 房间的日历类型转换器(Kotlin)

java - 在没有对象映射器的情况下将对象转换为 Jackson 中的 JSON 文件