Search code examples
javabigdecimal

Format of BigDecimal number


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

Solution

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