Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precision lost in float value using java

Given below the test code and its output. When I get float value from number value, precision is lost.. Can anyone tell me why this behaviour and also how to handle this?

public static void main(String[] args)
    {
        try
        {
            java.lang.Number numberVal = 676543.21;
            float floatVal = numberVal.floatValue();
            System.out.println("Number value    : " + numberVal);
            System.out.println("float value     : " + floatVal);
            System.out.println("Float.MAX_VALUE : " + Float.MAX_VALUE);
            System.out.println("Is floatVal > Float.MAX_VALUE ? " + ( floatVal > Float.MAX_VALUE));
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }

output:

    Number value    : 676543.21
    float value     : 676543.2
    Float.MAX_VALUE : 3.4028235E38
    Is floatVal > Float.MAX_VALUE ? false

also why the float value lesser than Float.MAX_VALUE?

like image 232
user1355253 Avatar asked Aug 06 '12 09:08

user1355253


People also ask

What is the precision of float in Java?

Floats can represent decimal values up to 7 digits of precision, and double can represent decimal values up to 16 digits of precision.

Why do floats lose precision?

Floating-point decimal values generally do not have an exact binary representation. This is a side effect of how the CPU represents floating point data. For this reason, you may experience some loss of precision, and some floating-point operations may produce unexpected results.


1 Answers

floats are usually good up to 6 significant digits. Your number is 676543.21 which has 8 significant digits. You will see errors past 6 digits, and those errors will easily propagate to more significant digits the more calculations you perform. If you value your sanity (or precision), use doubles. Floats can't even count past 10 million accurately.

Now, you have 2 significant digits, which suggests to me that there is a chance you want to represent currency - DO NOT . Use your own class that internally represents values using fixed-point arithmetic.

Now, as to Float.MAX_VAL which is 3.4028235E38, meaning 3.4028235*10^38 which is about 10^32 times larger than your value. Notice the 'E' in there? That's the exponent.

like image 151
Tassos Bassoukos Avatar answered Oct 04 '22 04:10

Tassos Bassoukos