javascript - how to prevent toFixed from rounding off decimal numbers

TheOnlyIdiot picture TheOnlyIdiot · May 30, 2012 · Viewed 27.4k times · Source

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.

Answer

David picture David · May 25, 2017

That's even simpler:

function truncateToDecimals(num, dec = 2) {
  const calcDec = Math.pow(10, dec);
  return Math.trunc(num * calcDec) / calcDec;
}

So:

truncateToDecimals(123456.786) -> 123456.78