英文:
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>.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论