Format of BigDecimal number

谁说胖子不能爱 提交于 2019-12-29 08:05:37

问题


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

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

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");

or

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

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));

回答1:


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

BigDecimal val = new BigDecimal("0.20");

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




回答2:


BigDecimal remembers the trailing zeros - with some significant side-effect:

BigDecimal bd1 = new BigDecimal("0.20"); 
BigDecimal bd2 = new BigDecimal("0.2");

System.out.println(bd1);
System.out.println(bd2);
System.out.println(bd1.equals(bd2));

will print

0.20
0.2
false

And we need to remember, that we can't use BiGDecimal for numbers, where the decimal expansion has a period:

BigDecimal.ONE.divide(new BigDecimal(3));

will throw an exception (what partially answers your concerns in your comments)




回答3:


You're passing a double to BigDecimal.valueOf(). And 0.20 is exactly the same double as 0.2. Pass it a String, and the result will be different, because the scale of the BigDecimal will be deduced from the number of decimals in the String:

BigDecimal bd1 = new BigDecimal("0.20");
BigDecimal bd2 = new BigDecimal("0.2");

System.out.println(bd1.toPlainString() + ", scale = " + bd1.scale()); // 0.20, scale = 2
System.out.println(bd2.toPlainString() + ", scale = " + bd2.scale()); // 0.2, scale = 1

NumberFormat nf = NumberFormat.getInstance();

nf.setMinimumFractionDigits(bd1.scale());
System.out.println(nf.format(bd1)); // 0,20 (in French locale)

nf.setMinimumFractionDigits(bd2.scale());
System.out.println(nf.format(bd2)); // 0,2 (in French locale)



回答4:


EDIT: this answer is wrong as pointed out in the comments :| thx Andreas_D

The problem is that there is no mathematical difference between 0.2 and 0.20 so your only chance is to display a certain number of digits after the decimal point. Once you store 0.2 or 0.20 in a BigDecimal they are indistinguishable from each other



来源:https://stackoverflow.com/questions/10653747/format-of-bigdecimal-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!