So, I've been having trouble trying to prevent toFixed from rounding up numbers, what I want to achieve is that, for a certain number, multiply that number to a specific number and then return the last two digits without rounding up.
I have read the following thread: javascript - how to prevent toFixed from rounding off decimal numbers.
As a matter of fact, I have tried the solution of Santiago Hernandez.
This is the fiddle: demo
Examples: 6500 * 0.0002 = 1.3
In this case, the result is 1. and does not take the 3 in consideration.
var multiplier = 0.0002;
var num = 500 * multiplier;
var toFixed = function(val, decimals) {
var arr = ("" + val).split(".")
if(arr.length === 1)
return val
var int = arr[0],
dec = arr[1],
max = dec.length - 1
return decimals === 0 ? int :
[int,".",dec.substr(0, decimals > max ? max : decimals)].join("")
}
I imagine is this part:
max = dec.length - 1
What I have tried:
I took out the - 1
and I tried with 10 different types of numbers (987.77, 6600.77, etc) but I wanted to know if there is another type of solution or if at some point the above code will fail for some digits.