Updated in 2023
There is one problem that no one has addressed: What to do with negative zeros ?
Should toFixed_norounding(-0.0000001, 2) be "-0.00" or "0.00" ?
In my application it is preferred to make it "0.00"
I created this updated version for negative and positive numbers, with tests, uncomment if you need negative zeros:
function toFixed_norounding(n,p)
{
var result = n.toFixed(p);
result = Math.abs(result) <= Math.abs(n) ? result: (result - Math.sign(n) * Math.pow(0.1,p)).toFixed(p);
// if you want negative zeros (-0.00), use this instead:
// return result;
// fixes negative zeros:
if(result == 0) return (0).toFixed(p);
else return result;
}
// tests:
[
["-1.99", -1.999999999999999,2],
["1.99", 1.999999999999999,2],
["-1.9", -1.999999999999999,1],
["1.9", 1.999999999999999,1],
["-1", -1.999999999999999,0],
["1", 1.999999999999999,0],
["4.56", 4.56, 2],
["-4.56", -4.56, 2],
["0.00", 0.00000000052, 2],
//["-0.00", -0.00000000052, 2], // allow negative zeros
["0.00", -0.00000000052, 2], // don't
["0.00", 0.000000000, 2],
["0.00", -0.000000000, 2],
["4.27", 4.27, 2],
["-4.27", -4.27, 2],
["0.00", 0.000000199, 2],
//["-0.00", -0.000000199, 2], // allow negative zeros
["0.00", -0.000000199, 2], // don't
["1234567.89", 1234567.89, 2],
["-1234567.89", -1234567.89, 2],
["4.999", 4.9999, 3],
["-4.999", -4.9999, 3],
].forEach( a => {
if(!( a[0] === toFixed_norounding(a[1],a[2]) )) console.log("test failed:", a, "result: ", toFixed_norounding(a[1],a[2]));
});
Fast, pretty, obvious.