0

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 Answers2

1

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());
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

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
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125