BigDecimal数的格式 [英] Format of BigDecimal number

查看:313
本文介绍了BigDecimal数的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BigDecimal val = BigDecimal.valueOf(0.20);
System.out.println(a);

我想在val中存储值0.20,而不是0.2.我能做什么?

I want to store in val a value 0.20 and not 0.2. What I can do ?

我不认为在这种情况下可以使用NumberFormat,当我使用NumberFormat时,我必须知道十进制数字的长度!我可以有0.20或0.5000,我不知道十进制数字的确切长度,所以我不能使用:

I dont think I can use NumberFormat in this case, when I use NumberFormat I must know what the length of my decimal number is! I can have 0.20 or 0.5000, I don't know the exact length of my decimal number, so I cannot use :

DecimalFormat df = new DecimalFormat("#0.00");

DecimalFormat df = new DecimalFormat("#0.00000");

也许我点后只有2个数字,或者5个或更多数字,但是该程序无法工作:

maybe I have just 2 numbers after point or 5 numbers or more, and this program doesn't work:

 BigDecimal a = BigDecimal.valueOf(0.20);//i give an example of 0.2 i can have 0.98...0
         System.out.println(a);

         NumberFormat nf1 = NumberFormat.getInstance();
         System.out.println(nf1.format(0.5000));

推荐答案

您可以使用BigDecimal的String构造函数.它保留了比例尺(这就是您想要的).

You could use the String constructor of BigDecimal. It preserves the scale (which is what you want).

BigDecimal val = new BigDecimal("0.20");

请参见 http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String )

这篇关于BigDecimal数的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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