Java – BigDecimal number format

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

I want to store a value of 0.20 instead of 0.2 in val What can I do?

In this case, I don't think I can use numberformat. When I use numberformat, I must know the length of my decimal number! I can have 0.20 or 0.5000. I don't know the exact length of my decimal number, so I can't use:

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

or

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

Maybe I only have 2 numbers or 5 or more numbers, 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));

Solution

You can use BigDecimal's string constructor It retains scale (that's 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)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>