bigDecimals 和 decimalFormat 的科学记数法
Scientific notation with bigDecimals and decimalFormat
我正在尝试使用 bigdecimals 和 decimalFormat 以科学记数法显示小数,这是我目前的想法:
BigDecimal a = new BigDecimal("0.000001");
DecimalFormat df = new DecimalFormat("0.0###E0");
System.out.println(df.format(a));
这个程序输出“1.0E-4”,这正是我想要的。现在,如果我将 bigDecimal 设置为“0.2222”,则输出为 2.222E-1。
我的问题是:在这种情况下有什么方法可以防止科学计数法,所以输出应该是 0.2222 而不是 2.222E-1?
尝试使用 g
格式说明符 String.format
。文档是 here.
下面是一些示例代码:
import java.math.BigDecimal;
public class BigDecTest {
public static final void main(String[] args) {
BigDecimal a = new BigDecimal("0.000001");
System.out.println(String.format("%6.4G",a));
BigDecimal b = new BigDecimal("0.2222" );
System.out.println(String.format("%6.4G", b));
}
}
它产生:
1.000E-06
0.2222
我正在尝试使用 bigdecimals 和 decimalFormat 以科学记数法显示小数,这是我目前的想法:
BigDecimal a = new BigDecimal("0.000001");
DecimalFormat df = new DecimalFormat("0.0###E0");
System.out.println(df.format(a));
这个程序输出“1.0E-4”,这正是我想要的。现在,如果我将 bigDecimal 设置为“0.2222”,则输出为 2.222E-1。
我的问题是:在这种情况下有什么方法可以防止科学计数法,所以输出应该是 0.2222 而不是 2.222E-1?
尝试使用 g
格式说明符 String.format
。文档是 here.
下面是一些示例代码:
import java.math.BigDecimal;
public class BigDecTest {
public static final void main(String[] args) {
BigDecimal a = new BigDecimal("0.000001");
System.out.println(String.format("%6.4G",a));
BigDecimal b = new BigDecimal("0.2222" );
System.out.println(String.format("%6.4G", b));
}
}
它产生:
1.000E-06
0.2222