In my JAVA program there is code like this:
int f_part = (int) ((f_num - num) * 100);
f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it’s value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don’t know why this happening. Please can someone explain why this happens and way to correct it.
This is due to the limited precision in doubles.
The root of your problem is that the literal
123.55actually represents the value123.54999....It may seem like it holds the value
123.55if you print it:but in fact, the printed value is an approximation. This can be revealed by creating a
BigDecimalout of it, (which provides arbitrary precision) and print the BigDecimal:You can solve it by going via
Math.roundbut you would have to know how many decimals the source double actually entails, or you could choose to go through the string representation of the double in fact goes through a fairly intricate algorithm.If you’re working with currencies, I strongly suggest you either
BigDecimalwhich allows you to store numbers as0.1accurately, orintstore the number of cents (as opposed to having a double store the number of dollars).Both ways are perfectly acceptable and used in practice.