强制BigDecimals使用科学记数法 [英] Forcing BigDecimals to use scientific notation

查看:705
本文介绍了强制BigDecimals使用科学记数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法:

    public void Example(BigDecimal value, int scale){
    BigDecimal x = new BigDecimal("0.00001");
    System.out.println("result: " + (value.multiply(x)).setScale(scale, RoudingMode.HALF_UP).toString());

如果,例如,值= 1且scale = 2,则输出为result:0.00 。我以为它会是1.00E-5。因此,我的疑问是:如果BigDecimal的比例大于某个值(在我的例子中它是2),我怎么能强制用科学记数法格式化呢?

If, per example, value = 1 and scale = 2, the output is "result: 0.00". I thought it would be 1.00E-5. So, my doubt is: How can I force a BigDecimal to be formated in scientific notation if its scale is bigger than a certain value (it was 2 in my example) ?

推荐答案

您可以使用 DecimalFormat setMinimumFractionDigits(int scale)

private static String format(BigDecimal x, int scale) {
  NumberFormat formatter = new DecimalFormat("0.0E0");
  formatter.setRoundingMode(RoundingMode.HALF_UP);
  formatter.setMinimumFractionDigits(scale);
  return formatter.format(x);
}
...
System.out.println(format(new BigDecimal("0.00001"), 2)); // 1.00E-5
System.out.println(format(new BigDecimal("0.00001"), 3)); // 1.000E-5

这篇关于强制BigDecimals使用科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆