I'm very new to html, javascript, and css so please forgive if my question sounds idiotic to you. My question is how can I prevent the function toFixed()
from rounding of the decimal number.
Here's my link: http://jsfiddle.net/RWBaA/4/
What I'm trying to do is I'm checking the input if its a valid decimal number whenever the user types in the textbox. At the same time I also want to check if the input is a valid currency which means it can only add two more numbers at the right of the decimal point. The problem is when the user enters the 3rd number after the decimal point the 2nd number after the decimal point is rounded off to the nearest hundredths if the the 3rd number is >= 5.
Test Input :
Input Output 123456.781 -> 123456.78 123456.786 -> 123456.79
Why my code does not allow arrow keys in chrome?
Please help. If you have a better solution you are free to suggest. Thanks in advance.
Round the number (down) to the nearest cent first:EDIT It's been pointed out that this fails for e.g. 1.13. I should have known better myself!
This fails because the internal floating point representation of 1.13 is very slightly less than 1.13 - multiplying that by 100 doesn't produce 113 but 112.99999999999998578915 and then rounding that down takes it to 1.12
Having re-read the question, it seems that you're really only trying to perform input validation (see below), in which case you should use normal form validation techniques and you shouldn't use
.toFixed()
at all. That function is for presenting numbers, not calculating with them.