【问题标题】:How to make a number with proper commas round to exactly 2 decimal places?如何使用正确的逗号将数字精确到小数点后 2 位?
【发布时间】:2020-11-30 04:43:16
【问题描述】:

在我的代码中,我正在尝试使用 Javascript 转换不同货币的计算器。我希望最终结果采用美国形式的适当逗号形式,例如,如果数字是 1000000.3,我希望它显示为 1,000,000.30

我尝试使用 toFixed、toLocaleString 和 parseFloat,使用 toFixed 舍入到小数点后 2 位,使用 toLocaleString 进行正确的逗号格式设置,并使用 parseFloat 将 toFixed 和 toLocaleString 转换为数字,以便它们可以相互操作.

问题是,当我使用 toFixed 然后使用 toLocaleString 时,toFixed 会使原始数字为 1000000.30,但随后 toLocaleString 会去掉最后的 0,使最终结果为 1,000,000.3。或者,当我尝试颠倒顺序并使用 toLocaleString 然后使用 toFixed 时,toLocaleString 使其变为 1,000,000.3,但随后 toFixed 将第一个逗号视为小数,使最终结果为 1,000 而不是 1,000,000.30。有什么我遗漏的东西或我不知道的不同策略吗?我对编码很陌生,所以欢迎所有建议:)

(下面代码的输出可以在这里看到:https://xrpalerts.000webhostapp.com/testing_ground.html

<!DOCTYPE html>
<html>
<body>

<script>

var CalculatorResult = 1000000.3
var CalculatorResultLocale = parseFloat(CalculatorResult).toLocaleString("us-EN");
var CalculatorResultLocaleFixed = parseFloat(CalculatorResultLocale).toFixed(2);

document.write(CalculatorResultLocale);
</script>
<br>

<script>
document.write(CalculatorResultLocaleFixed);
</script>
<br>
<br>
<script>
var CalculatorResultFixed = parseFloat(CalculatorResult).toFixed(2);
var CalculatorResultFixedLocale = parseFloat(CalculatorResultFixed).toLocaleString("us-EN");

document.write(CalculatorResultFixed);
</script>
<br>
<script>
document.write(CalculatorResultFixedLocale);
</script>



</body>
</html>

【问题讨论】:

    标签: javascript numbers currency cryptocurrency


    【解决方案1】:

    你可以这样做

    var formatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    });
    var num1 = 1000000.3
    console.log(formatter.format(num1))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-08
      • 2021-03-12
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多