Josh
Josh

Reputation: 598

Javascript toFixed() no trailing zeros

I'm tired and this is maths. Should be fairly simple, and good chance I get it while typing this out.

I have a function, let's call it roundNumber

function roundNumber(value){
    return value.toFixed(3);
}

But I want to round to 3 decimal, unless the succeeding digits are 0. Desired result:

roundNumber(1/3) //Should output 0.333
roundNumber(1/2) //Should output 0.5, NOT 0.500
roundNumber(1/8) //Should output 0.125
roundNumber(1/4) //Should output 0.25

Best way to do this?

Upvotes: 3

Views: 1380

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074058

First off: What the function does is not just rounding. It converts a number to a string (doing some rounding along the way).

If you really want a string, your best bet is probably to trim off trailing zeros that don't have a . in front of them:

return value.toFixed(3).replace(/([^.])0+$/, "$1");

Live Example:

function roundNumber(value) {
    return value.toFixed(3).replace(/([^.])0+$/, "$1");
}
console.log(roundNumber(1/3)); //Should output 0.333
console.log(roundNumber(1/2)); //Should output 0.5, NOT 0.500
console.log(roundNumber(1/8)); //Should output 0.125
console.log(roundNumber(1/4)); //Should output 0.25

Upvotes: 5

Rory McCrossan
Rory McCrossan

Reputation: 337560

To do what you require you can convert the string result of toFixed() back to a numerical value.

The example below uses the + unary operator to do this, but Number() or parseFloat() would work just as well.

function roundNumber(value) {
  return +value.toFixed(3);
}

console.log(roundNumber(1 / 3)) //Should output 0.333
console.log(roundNumber(1 / 2)) //Should output 0.5, NOT 0.500
console.log(roundNumber(1 / 8)) //Should output 0.125
console.log(roundNumber(1 / 4)) //Should output 0.25

Upvotes: 4

Related Questions