Problem with toFixed() Javascript method

Asked

Viewed 56 times

3

The method toFixed(2) leaves the number with two decimal places, but when the number is finished in 5 it rounds up and I’d like it to round down. Is there any way?

Example:

let num = 10.125
num = num.toFixed(2); //num = 10.13

In that case the result I need is num = 10.12

  • In fact if you take the number without arrendondar?

2 answers

3

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);

2

You can use the toFixed with decimals plus and then cut the last value...

const toNotRoundedFixed = (nr, fixed) => nr.toFixed(fixed + 3).slice(0, -3)

const num = 10.125
console.log(num.toFixed(2)) // 10.13
console.log(toNotRoundedFixed(num, 2)) // 10.12

Browser other questions tagged

You are not signed in. Login or sign up in order to post.