Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

possible loss of precision error in java

Tags:

java

This is my code:

class test{

    public static void main(String arg[]){

        int a=10, b=20;
        float c = 30.123;
        int e = (int)c;
        System.out.println(e);

    }
}

I'm getting this error:

test.java:6: error: possible loss of precision
        float c = 30.123;
                  ^
required: float
found:    double
1 error

Why all these?

like image 433
Shafny Avatar asked Feb 12 '13 18:02

Shafny


2 Answers

Floating point literals are by default of double type. And assigning a double value to a float type will result in some precision error. You can either change the type of c to double, or append an f at the end of it to make it float like so:

float c = 30.123f;
like image 148
Rohit Jain Avatar answered Nov 18 '22 08:11

Rohit Jain


If you specify float value without f at the end it is treated as double which is by-default.

double d = 30.123;

For float literal you should append f at the end of float value.

float c = 30.123f;
like image 26
Subhrajyoti Majumder Avatar answered Nov 18 '22 09:11

Subhrajyoti Majumder