在使用 BigDecimal 时防止在 Java 中为 Android 转换为指数格式
Prevent conversion to exponent format in Java for Android while using BigDecimal
我正在尝试使用 Android 中 Java 中的 BigDecimal 将 5 除以 0.0005。
我得到的结果是 1E+4 而我想显示 10000 作为结果。
现在我正在做的是:
BigDecimal aaaa = new BigDecimal("5");
BigDecimal bbbb = new BigDecimal("0.0005");
aaaa.divide( bbbb , new MathContext( 16, RoundingMode.DOWN) );
我想要 16 位精度 RoundingMode.DOWN
场景 1:未按预期工作
aaaa = 5
bbbb = 0.0005
result => 1E+4
required => 10000
场景 2:按预期工作
aaaa = 100
bbbb = 3
result => 33.33333333333333
required => 33.33333333333333
为什么两个答案的输出 format 完全相同,代码完全相同。有办法解决吗?
Returns the string representation of this BigDecimal, using scientific
notation if an exponent is needed.
Returns a string representation of this BigDecimal without an exponent
field.
public static void main(String[] args) {
BigDecimal aaaa = new BigDecimal("5");
BigDecimal bbbb = new BigDecimal("0.0005");
BigDecimal result = aaaa.divide( bbbb , new MathContext( 16, RoundingMode.DOWN) );
System.out.print(result.toPlainString()); //10000
}
很简单。我通过使用
得到了我想要的
BigDecimal.stripTrailingZeros().toPlainString();
不使用DecimalFormat
,这显示了我需要的输出
5 / 0.0005 => 10000 (and not in exponential format as => 1E+4)
100 / 3 => 33.33333333333333
我正在尝试使用 Android 中 Java 中的 BigDecimal 将 5 除以 0.0005。
我得到的结果是 1E+4 而我想显示 10000 作为结果。
现在我正在做的是:
BigDecimal aaaa = new BigDecimal("5");
BigDecimal bbbb = new BigDecimal("0.0005");
aaaa.divide( bbbb , new MathContext( 16, RoundingMode.DOWN) );
我想要 16 位精度 RoundingMode.DOWN
场景 1:未按预期工作
aaaa = 5
bbbb = 0.0005
result => 1E+4
required => 10000
场景 2:按预期工作
aaaa = 100
bbbb = 3
result => 33.33333333333333
required => 33.33333333333333
为什么两个答案的输出 format 完全相同,代码完全相同。有办法解决吗?
Returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.
Returns a string representation of this BigDecimal without an exponent field.
public static void main(String[] args) {
BigDecimal aaaa = new BigDecimal("5");
BigDecimal bbbb = new BigDecimal("0.0005");
BigDecimal result = aaaa.divide( bbbb , new MathContext( 16, RoundingMode.DOWN) );
System.out.print(result.toPlainString()); //10000
}
很简单。我通过使用
得到了我想要的BigDecimal.stripTrailingZeros().toPlainString();
不使用DecimalFormat
5 / 0.0005 => 10000 (and not in exponential format as => 1E+4)
100 / 3 => 33.33333333333333