Nick Silicon
Nick Silicon

Reputation: 71

Float - datatype confusion

class Test
{
    public static void main(String[] arg2) 
    {
        float num = 1234.123126f;
        System.out.println(num);
    }
}

Output: 1234.1232 Why it is not 1234.123 or 1234.1231?

Upvotes: 2

Views: 95

Answers (4)

Hiren
Hiren

Reputation: 130

This is occurring because of rounding of the exact value. If you want to print the exact value as it is, you will have to specify the format using examples given in this Oracle tutorial.

Upvotes: 0

Rick Regan
Rick Regan

Reputation: 3512

First of all, a float can only reliably store up to 6 digits; 1234.123126 is too long to store as a float and recover as a decimal exactly.

Java prints a decimal string that allows you to recover the internal float value. In the worst case, 9 decimal digits are required, but less can suffice. The internal float value of 1234.123126 is 1234.1231689453125. Rounded to 9 digits, that's 1234.12317. But 1234.1232 converts to the same float, and is shorter, so Java chooses that. (Note that 1234.123 and 1234.1231 are incorrect choices, since they convert to a different float: 1234.123046875.

Upvotes: 0

castletheperson
castletheperson

Reputation: 33466

System.out.println(float) calls String.valueOf(float), which calls Float.toString(float).

The answer is in the documentation for Float.toString(float):

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type float.

Therefore, it printed 1234.1232 because it is the closest value representable by the float data-type that is uniquely identifiable from any adjacent float values.

Upvotes: 4

anacron
anacron

Reputation: 6711

I see your point. Your rounding logic is correct. But, since you're using a float datatype, you will be losing some amount of precision. So, when the JVM does the rounding, it is arriving at the value of 1234.1232.

Upvotes: 0

Related Questions