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

javascript - Format number to 2 decimal places only if it has decimal places - Stack Overflow

programmeradmin1浏览0评论

I want d3 to format my number to 2 decimal places, only if it has decimal value. Also, I want it to work with one single format function.

For now, I have been using this. Is there any way I can improve this to be able to work around?

d3.format(",.2f")(10101); //10,101.00 which must be displayed as 10,000 only

d3.format(",.2f")(12334.2); //12,334.20 this is okay

I want d3 to format my number to 2 decimal places, only if it has decimal value. Also, I want it to work with one single format function.

For now, I have been using this. Is there any way I can improve this to be able to work around?

d3.format(",.2f")(10101); //10,101.00 which must be displayed as 10,000 only

d3.format(",.2f")(12334.2); //12,334.20 this is okay
Share Improve this question edited Jan 28, 2017 at 13:53 Gerardo Furtado 102k9 gold badges128 silver badges176 bronze badges asked Jan 28, 2017 at 13:37 Sabbiu ShahSabbiu Shah 1,7093 gold badges19 silver badges28 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

I want it to work with one single format function

Well, that's not possible. D3 format functions cannot adapt to the number you pass to them like that.

However, you can have two format functions, and test to see if the number you're passing has or has not decimal places. This is one possible way to test:

number % 1

Which returns 0 for integers.

Then, in a ternary operator, you can choose which d3.format function you'll use:

!(number % 1) ? someFormat(number) : otherFormat(number)

Here is a demo:

var formatInteger = d3.format(",");
var formatDecimal = d3.format(",.2f");

var number1 = 10101;
var number2 = 12334.2;

function format(number){
return !(number % 1) ? formatInteger(number) : formatDecimal(number)
}

console.log(format(number1))
console.log(format(number2))
<script src="https://d3js.org/d3.v4.min.js"></script>

The closest you can get to that is if you use the '~' to remove any trailing zeroes. So in your case, the format would ',.2~f'.

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script>
console.log(d3.format(",.2~f")(10101));
console.log(d3.format(",.2~f")(12334.2));
</script>

More info about d3-format here: https://observablehq.com/@d3/d3-format

You can try this:


const formattedValue = value >= 100000
                ? value % 1 === 0
                  ? SI(value).replace(".0", "")
                  : SI(value)
                : value
发布评论

评论列表(0)

  1. 暂无评论