I have some simple javascript which I want to use to determine if a number needs to be rounded.
Example: User enters 1.2346 and the number is rounded to 1.235 and a message should be displayed to the user informing them that the number was rounded.
Rounding the number isn’t the issue, but showing the error message to the user is. I need to find the number of digits after the decimal point.
I use the following code to retrieve the decimal places off of a string. I then count the length of the variable to get the decimal places:
var dp = field_value - Math.floor(field_value);
However, When I test this I enter 1.23 for the value of field_value. When I check the value of field value it is indeed 1.23. When I check the value of Math.floor(field_value) it is indeed 1. But then I check the value of dp and it turns out to be 0.22999999999999998
Why does this subtraction not work the way it is expected?
Problem is given by the fact that floating numbers have a finite representation, take a look here and you will understand how and why.
If problem with roundings is just for printing that number you could use something like sprintf for JS that allows you to format float output as you nee.