Javascript 如何将带有正确逗号的数字精确舍入到小数点后2位?

Javascript 如何将带有正确逗号的数字精确舍入到小数点后2位?,javascript,numbers,currency,cryptocurrency,Javascript,Numbers,Currency,Cryptocurrency,在我的代码中,我试图拥有一个使用Javascript转换不同货币的计算器。我希望最终结果是在美国格式中使用正确的逗号,因此,例如,如果数字是1000000.3,我希望它显示为1000000.30 我尝试过使用toFixed、tolocalstring和parseFloat,使用toFixed四舍五入到小数点后2位,使用tolocalstring生成正确的逗号格式,使用parseFloat将toFixed和tolocalstring转换为数字,以便它们可以相互操作 问题是,当我使用toFixed,

在我的代码中,我试图拥有一个使用Javascript转换不同货币的计算器。我希望最终结果是在美国格式中使用正确的逗号,因此,例如,如果数字是1000000.3,我希望它显示为1000000.30

我尝试过使用toFixed、tolocalstring和parseFloat,使用toFixed四舍五入到小数点后2位,使用tolocalstring生成正确的逗号格式,使用parseFloat将toFixed和tolocalstring转换为数字,以便它们可以相互操作

问题是,当我使用toFixed,然后使用tolocalString时,toFixed会使原来的数字变成1000000.30,但是tolocalString会去掉最后的0,使最终结果变成1000000.3。或者,当我尝试颠倒顺序并使用toLocaleString和toFixed时,toLocaleString使其为1000000.3,但toFixed将第一个逗号视为十进制,使最终结果为1000而不是1000000.30。是否有什么我遗漏的或是我不知道的不同策略?我对编码相当陌生,所以欢迎所有建议:)

(下面代码的输出可以在这里看到:)


var CalculatorResult=1000000.3
var CalculatorResultLocale=parseFloat(CalculatorResult).toLocaleString(“us-EN”);
var calculatorresultlocalefix=parseFloat(CalculatorResultLocale).toFixed(2);
编写(CalculatorResultLocale);

document.write(CalculatorResultLocaleFixed);

var CalculatorResultFixed=parseFloat(CalculatorResult).toFixed(2); var CalculatorResultFixedLocale=parseFloat(CalculatorResultFixed).toLocaleString(“us-EN”); 文件。编写(CalculatorResultFixed);
编写(CalculatorResultFixedLocale);
你可以这样做
var formatter=new Intl.NumberFormat('en-US'{
风格:“货币”,
货币:美元,
});
var num1=1000000.3
console.log(formatter.format(num1))
<!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>