Skip to content
Advertisement

How to get the decimal part of a float?

I need to extract the decimal part of a float number, but I get weird results:

JavaScript

Why does this happen? Why do I get those values instead of 0.65?

Advertisement

Answer

float only has a few digit of precision so you should expect to see a round error fairly easily. try double this 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.

JavaScript

Prints

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement