我需要将这两个字符串 "0.0000000" 和 "0.0000008" 转换为 BigDecimal,而不丢失尾随 0。
我尝试过 String.format
String format = "%." + precision + "f";
BigDecimal divisor = new BigDecimal(Math.pow(10, precision));
formattedAmount = amountValue.divide(divisor).setScale(precision, BigDecimal.ROUND_DOWN);
String str= String.format(format, formattedAmount);
System.out.println(str);
BigDecimal strb = new BigDecimal(str);
System.out.println(strb);
我期望这两个字符串 "0.0000000" 和 "0.0000008" 以 BigDecimal 形式返回,而不带像 0.0000000 和 这样的指数0.0000008。但我得到了 0E-7 和 8E-7。 我需要 0.0000000 和 0.0000008 作为 BigDecimal 而不是 String。
最佳答案
当您尝试在 System.out.println(strb)
中打印 BigDecimal 时toString()
方法strb
对象将被调用。所以控制台的输出也是字符串。
查看更多The connection between 'System.out.println()' and 'toString()' in Java
所以告诉java不要在这里使用指数的唯一方法System.out.println(strb)
就是改toString()
方法。您不能直接更改它,但您可以创建自己的类来扩展 BigDecimal
并覆盖toString()
你需要的方法。显然这没有意义..只需使用 toPlainString()
方法。来自java文档:
return a string representation of this {@code BigDecimal} without an exponent field.
关于java - 如何在将字符串转换为不带指数的 BigDecimal 时保持尾随 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58005398/