If the idea is to leave only 2 decimal places, just make some simple calculations:
- first you multiply by 100, the result will be
1012.5
- then round down, resulting in
1012
- finally, divide by 100, the result will be
10.12
let num = 10.125;
num = Math.floor(num * 100) / 100;
console.log(num); // 10.12
Generally speaking, if you want to keep only N decimal places, just do the above process for 10N. I mean, you can generalize the code above:
function manterCasas(num, casas) {
let n = Math.pow(10, casas);
return Math.floor(num * n) / n;
}
let num = 10.125;
console.log(manterCasas(num, 2)); // 10.12
console.log(manterCasas(num, 1)); // 10.1
There’s only one detail: toFixed
returns a string, while the above codes return a number. Of course, when printing, both are shown in the same way, but it is not clear which one you want (since depending on what you will do with this data later, can make a difference).
But anyway, if you want a string, just take the result and call .toString()
(would no longer need toFixed
because the value is already with the desired amount of decimal places):
let num = 10.125;
// se quiser o resultado como uma string
let numString = (Math.floor(num * 100) / 100).toString();
console.log(numString);
In fact if you take the number without arrendondar?
– novic