Reputation: 3415
I tried running the following code:
double f = 4.35;
int n = (int) (100 * f);
n
will be 434
. Why?
Upvotes: 1
Views: 187
Reputation: 236140
Try this instead:
double f = 4.35;
int n = (int) Math.round(100 * f);
Now n
will have as value 435
, as expected. This kind of problems happen because of rounding errors when dealing with decimal values represented in base 2, take a look at this reference to find out more: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Upvotes: 1
Reputation: 27125
4.35 cannot be represented exactly as a floating-point number since .35 is not a (negative) power of 2. As a result, there's a bit of roundoff one way or another. There will probably also be roundoff when you multiply by 100. If the resulting number is a bit less than 435, casting to int will take the floor of it, which is 434.
If you'd like to round to the NEAREST integer, you can add 0.5 to the result and then cast to int. This is the most general way to round numbers, although Java has a built-in implementation of rounding.
double f = 4.35;
int n = (int) (100 * f + 0.5);
Upvotes: 2
Reputation: 2625
this is because floating point numbers are internally represented in base 2 not base 10.
this here will help (have to import Math
):
double f = 4.35;
long n = Math.round(100 * f);
Upvotes: 0
Reputation: 25757
You need to watch this. I made first year uni students watch it for homework. http://vimeo.com/7403673 - Jon Skeet and Tony the Pony.
Jon Skeet's presentation at the London Stack Overflow DevDays event: stackoverflow.carsonified.com
At around 6:50 he talks about maths in Java and some of the common problems faced by developers with regards to maths.
Upvotes: 1