从DecimalFormat.format()获取大量错误结果

问题描述 投票:0回答:1
val numberFormatter = NumberFormat.getNumberInstance(Locale.getDefault())
val conversionPattern = "#,##0.####"
val decimalFormatter = numberFormatter as DecimalFormat
decimalFormatter.applyPattern(conversionPattern)

decimalFormatter.format("9999999999999999".toDouble()) // Getting -> "10,000,000,000,000,000"
                                                       // Need    ->  "9,999,999,999,999,999"

怎么了?它溢出了吗?我正在处理非常大的数字,因此我将BigDecimal用于基础值,但要使用分组分隔符对其进行格式化,则没有接受BigDecimal的format()函数。如何格式化至少20位的数字?

java kotlin bigdecimal integer-overflow decimalformat
1个回答
2
投票
将BigDecimal或BigInteger用于如此大的数字。例如:

decimalFormatter.format(new BigDecimal("9999999999999999"))

A double精度浮点数仅具有大约15-16个十进制数字精度。您的电话号码有16个9。没有精确等于9999999999999999的双精度浮点数,因此将其舍入为最接近的数字-恰好是10 

16。

© www.soinside.com 2019 - 2024. All rights reserved.