简体   繁体   English

仅当数字有小数位时,才将数字格式化为 2 个小数位

[英]Format number to 2 decimal places only if it has decimal places

I want d3 to format my number to 2 decimal places, only if it has decimal value.我希望 d3 将我的数字格式化为 2 个小数位,前提是它有十进制值。 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 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. D3 格式函数无法适应您传递给它们的数字。

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.对于整数,它返回 0。

Then, in a ternary operator , you can choose which d3.format function you'll use:然后,在三元运算符中,您可以选择要使用的d3.format函数:

!(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'.所以在你的情况下,格式是',.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有关 d3-format 的更多信息,请访问: https : //observablehq.com/@d3/d3-format

You can try this:你可以试试这个:


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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