BigDecimal number format

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

I want to keep the value in val 0.20, not 0.2. What can I do?

I do not think that I can use NumberFormatin this case, when I use NumberFormat, I should know what the length of my decimal number is! I can have 0.20 or 0.5000, I do not know the exact length of the decimal number, so I can not use:

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

or

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

Perhaps I have only 2 numbers after the point or 5 numbers or more, and this program does not 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));
+3
source share
4 answers

You can use the String BigDecimal constructor. It saves the scale (which 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 )

+3

BigDecimal - :

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

0.20
0.2
false

, BiGDecimal , :

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

( )

+7

double BigDecimal.valueOf(). 0.20 0.2. , , BigDecimal 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)
+3

EDIT: , : | Andreas_D

, 0.2 0.20, - . 0.2 0.20 BigDecimal,

0