簡體   English   中英

如何使用正確的逗號將數字精確到小數點后 2 位?

[英]How to make a number with proper commas round to exactly 2 decimal places?

在我的代碼中,我試圖有一個使用 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。 有什么我遺漏的東西或我不知道的不同策略嗎? 我對編碼很陌生,所以歡迎所有建議:)

(下面代碼的output可以在這里看到: 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>

你可以這樣做

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM