0

I have a piece of code as below.

String wtf = "8.40";
float ft = Float.parseFloat(wtf); //8.4
ft *= 100.0F;

the value of "ft" above is coming as 839.99994

I expected output as 840.00000 How can I correct my code so that it gives me 840.00000 as output

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257

2 Answers2

0

Use Double.valueOf(wtf) instead of Float.parseFloat(wtf)

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
0
    String wtf = "8.40";
    double ft = Double.parseDouble(wtf); //8.4
    ft *= 100.0F;

There's is a lot of rounding when you use float. This is why you get this "unexpected" value. And I use parseDouble because the cost is less.

I suggest using BigDecimal for arithmetic and calculations.

BigDecimal BDa = new BigDecimal("8.40");
BigDecimal BDc = BDa.multiply(new BigDecimal("100.0"));
fneron
  • 1,057
  • 3
  • 15
  • 39