最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript toFixed() no trailing zeros - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Dec 2, 2020 at 15:36 JoshJosh 6481 gold badge6 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

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

发布评论

评论列表(0)

  1. 暂无评论