簡體   English   中英

我希望我的代碼只顯示 2 位小數

[英]I would like my code to only show 2 decimal places

我編寫了這段代碼,當我執行它時,它最多顯示 10 位小數。 我想知道是否有辦法刪除多余的小數位。

現在,我試過這個:

價格=價格.tofixed(2);

但這似乎不起作用,我不明白為什么。

<script>
var weight = parseFloat(prompt("weight in lbs", "10"));
weight = weight.toFixed(2);
var price;
price= price.tofixed(2);


// writes down the volumes of triangles-->
document.write("<p>the weight is  : "+weight+"</p>");

</script>

<script>
// else if statements which will calculate the price of the shipping -->
if(weight <= 2) price=weight*1.10;
else if (weight>=2 && weight<=6) price=weight*2.20;
else if(weight>6 && weight<=10) price=weight*3.70;
else if(weight>10) price=weight*3.80;

document.write("<p>the price of the item's shipping is  "+price+"</p>");
</script>
  
</script>
</body>
</html>

由於您希望將值格式化為貨幣金額,您可以像這樣使用Intl.NumberFormat

document.write("<p>the price of the item's shipping is  "+ 
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price) +
"</p>");

您需要在分配price后調用price.toFixed 例如:

else if(weight>10) price=weight*3.80;

price = price.toFixed(2);    

document.write("<p>the price of the item's shipping is  "+price+"</p>");

暫無
暫無

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

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