Losing precision converting from int to double in java -


i tried test following code, , gave me 434 on n, result did not anticipate, what's reason loss of precision?

double f = 4.35; int n =  (int) (100 * f); // n 434 - why? n = (int) math.round(100*f); // n 435 

floating point isn't perfect. uses approximated values.

in particular, doubles can not represent numbers. 1/3 can't precisely represented in decimal using finite number of digits, can't 4.35 represented in binary finite number of bits.

so rounded results. values close 4.35, not quite equal. in case, it's bit smaller, when multiply 100, don't 435, almost 435, not quite same.

when cast int, truncate result, 434,999... becomes 434.

in contrast, when use math.round, convert 434,999... 435 (which can represented precisely).

if precisely representing 4.35 necessary, take @ java bigdecimal type.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -