简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM