7
public class HelloWorld {

    public static void main(String[] args) {
        float amt = Float.valueOf("21111111.00");
        System.out.printf("%f\n", amt);

    }
}

Output is: 21111112.000000

Why is the float value being incremented by 1 automatically?

Boann
  • 48,794
  • 16
  • 117
  • 146
  • 1
    Isn't it just because `float`s don't have enough mantissa? – Sweeper Nov 27 '18 at 07:51
  • 5
    That is the nearest representative value. Try `double` instead. – Peter Lawrey Nov 27 '18 at 07:52
  • 1
    Floating-point types are inherently imprecise, and the precision of the type`float` is only about 6 or 7 decimal digits. – Jesper Nov 27 '18 at 07:52
  • Actually , it is giving a number greater than what i am passing, so i am within the range and error is not been thrown. Please suggest an better option. – Harsha Vardhan Nov 27 '18 at 07:57
  • Use `double`, this gives you about 15 decimal digits precision. – Henry Nov 27 '18 at 08:06
  • 1
    Float has limited precision (this is not the same as the range!) "21111111.00" cannot be represented as float - the nearest possible float values are "21111110" and "21111112" – Thomas Kläger Nov 27 '18 at 08:13
  • Even when i pass the 21111111, it doesn't return the equivalent number.What is the crux of using float in java and why it is returning a different number instead of an error. – Harsha Vardhan Nov 27 '18 at 09:33
  • 2
    There is no error. This number simply has too many significant digits to be exactly represented in a `float`. The result is as close to the true value as it can get. – Henry Nov 27 '18 at 09:45
  • float has only 24 bits of mantissa, which corresponds to ~7 digits of precision. 21111111 has 8 digits – phuclv Nov 27 '18 at 16:25

0 Answers0