简体   繁体   English

如何以人类可读的格式显示BigDecimal值?

[英]How to display BigDecimal value in a human readable format?

Suppose we have a BigDecimal variable setted up like this, and we can't change the way of it's creation: 假设我们有一个这样设置的BigDecimal变量,并且我们不能更改其创建方式:

BigDecimal num = new BigDecimal(6.0053);

So we'll see the following 'pretty' value after an output: 因此,在输出后,我们将看到以下“漂亮”值:

System.out.println(num);   //0053000000000000824229573481716215610504150390625

The only way I've found to resolve this problem was using BigDecimal.valueOf(): 我发现解决此问题的唯一方法是使用BigDecimal.valueOf():

System.out.println(BigDecimal.valueOf(num.doubleValue()));   //6.0053

But is there a more simple solution? 但是,有没有更简单的解决方案?

Thanks in advance. 提前致谢。

Use java.text.DecimalFormat to format the numbers. 使用java.text.DecimalFormat格式化数字。

NumberFormat format = new DecimalFormat("0.####");
System.out.println(format.format(num));

The format options can be found here 格式选项可以在这里找到

BigDecimal num = new BigDecimal(6.0053);
DecimalFormat df=new DecimalFormat("0.0000");
System.out.println(df.format(num));
System.out.println(new DecimalFormat("###,##0.00").format(myBigDecimalVariable));

You can use String.format with the " g " formatting type. 您可以将String.format与“ g ”格式类型一起使用。 It allows you to control how many digits you want, etc. See here for all formatting options. 它允许您控制所需的位数等。有关所有格式设置,请参见此处

BigDecimal num = new BigDecimal(6.0053);
String formated = String.format("%6.5g", num);
System.out.println(formated);

(Result : 6.0053 ) (结果: 6.0053

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM