【发布时间】: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