繁体   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