This site requires JavaScript, please enable it in your browser!
Greenfoot back
xxX_Muffin.man_Xxx
xxX_Muffin.man_Xxx wrote ...

2014/9/23

Need help with floats

xxX_Muffin.man_Xxx xxX_Muffin.man_Xxx

2014/9/23

#
I have this program i'm trying to do. Here's a very simplified version
int x = 3

double y = x * 1.2
 
It is very simple, but my problem is that when i print the number it is not 3.6 but 3.599999999999996 or something. All i want to do is have the ' y ' to 2 decimal places.
Super_Hippo Super_Hippo

2014/9/23

#
To round a double (here y) to 2 decimal places, you can do something like this:
y = ((int) (y*100)) / 100;
But I wonder how 3*1.2 is 3,599... for you.
davmac davmac

2014/9/23

#
'double' and 'float' cannot store decimal fractions exactly (they use a binary representation), which is why you see the apparent imprecision.
xxX_Muffin.man_Xxx xxX_Muffin.man_Xxx

2014/9/25

#
int x = 3  
  
double y = x * 1.2  
y = ((int) (y*100)) / 100; 

Now what happens when i print y is that it is 3.0
Super_Hippo Super_Hippo

2014/9/25

#
Ok, I don't know what is causing this, but if you add an extra step, it is working...
        int x = 3;
        double y = x * 1.2;
        y = (int) (y*100);
        y = y / 100;
        System.out.println(y);
You need to login to post a reply.