0
votes

If i divide 1.0f/2.0f , the value is 0.5 .

I wanted to have a precision value of 5 (0.50000). Used BigDecimal to set the scale to 5 but still the value is printed as 0.5

BigDecimal val = new BigDecimal(1.0f/2.0f);
BigDecimal tt = val.setScale(5); System.out.println(tt.doubleValue);

How to set the scale and to make it 0.50000. I mean pad extra zero if the precision value is less than the scale

E.g in this case 1/2 is always 0.5 (precision is 1) and if i want a higher precision (say 5) , how do i achieve it

Please advise

2
tt.doubleValue You just converted tt back into a number without any particular formatting whatsoever.Louis Wasserman
it was late night for me so passed out . Apologiesuser3491141

2 Answers

1
votes

Just print the BigDecimal

    BigDecimal val = new BigDecimal(1.0f/2.0f);
    BigDecimal tt = val.setScale(5); 
    System.out.println(tt);

or if you want to use a double, then your can use

    System.out.printf("%.5f%n", tt.doubleValue());
0
votes

use DecimalFormat :

BigDecimal a = new BigDecimal(1/2.0);
BigDecimal value = a.setScale(5, BigDecimal.ROUND_HALF_EVEN);
System.out.println(value);

The output is:

0.50000