I need to extract the decimal part of a float number, but I get weird results:
float n = 22.65f;
// I want x = 0.65f, but...
x = n % 1; // x = 0.6499996
x = n - Math.floor(n); // x = 0.6499996185302734
x = n - (int)n; // x = 0.6499996
Why does this happen? Why do I get those values instead of 0.65?
floatonly has a few digit of precision so you should expect to see a round error fairly easily. trydoublethis has more accuracy but still has rounding errors. You have to round any answer you get to have a sane output.If this is not desireable you can use BigDecimal which does not have rounding errors, but has its own headaches IMHO.
EDIT: You may find this interesting. The default Float.toString() uses minimal rounding, but often its not enough.
Prints