java - 对于大数字,从 DecimalFormat.format() 获取不正确的结果

标签 java kotlin bigdecimal integer-overflow decimalformat

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 位数字的格式?

最佳答案

对于如此大的数字,请使用 BigDecimal 或 BigInteger。例如:

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

double float 只有大约 15-16 位十进制数字的精度。你的数字有 16 个 9。不存在完全等于 9999999999999999 的 double float ,因此它会四舍五入到最接近的数字 - 恰好是 1016

关于java - 对于大数字,从 DecimalFormat.format() 获取不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61133353/

相关文章:

java - HMAC 一个 php 字节数组

kotlin - 如何以清晰的方式将 kotlin Map<String, String?> 转换为 Map<String, String>?

java - 如何从另一个模块访问 Spring Boot Quartz Bean?

java - 如何处理接近1的数的乘法

java - 我的 Java 应用程序中的离线奖励系统

java - 如何将 Collection<Set<String>> 转换为字符串数组

reflection - Kotlin - 获取 KProperty1<T, out R> 的属性类型

java - 解析流函数中的对象

biginteger - 如何计算 BigDecimal 中的数字?

java - 如何通过编码关闭/关闭Android平板电脑?