从DecimalFormat.format()对于大数值的获取结果不正确

huangapple go评论58阅读模式
英文:

Getting incorrect results from DecimalFormat.format() for large numbers

问题

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"

What's going wrong? Is it overflow? I am dealing with really large numbers so I'm using `BigDecimal` for the underlying value, but to format it with grouping separators, there's no `format()` function that accepts `BigDecimal`. How can I format numbers with at least 20 digits?
英文:
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"

What's going wrong? Is it overflow? I am dealing with really large numbers so I'm using BigDecimal for the underlying value but to format it with grouping separators there's no format() function that accepts BigDecimal. How can I format numbers with at least 20 digits?

答案1

得分: 2

使用BigDecimal或BigInteger来处理如此大的数字。例如:

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

double精度浮点数仅具有大约15-16位十进制数字的精度。您的数字有16个九。没有双精度浮点数能够精确地等于9999999999999999,因此它会四舍五入到最接近的一个数字——这恰好是10的16次方。

英文:

Use BigDecimal or BigInteger for numbers as large as this. For example:

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

A double precision floating point number has only around 15-16 decimal digits of precision. Your number has 16 nines. There is no double precision floating point number exactly equal to 9999999999999999, so it is rounded to the closest one - which happens to be 10<sup>16</sup>.

huangapple
  • 本文由 发表于 2020年4月10日 10:56:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/61133353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定