繁体   English   中英

舍入到小数点后两位

[英]Rounding to two decimal places issue

我使用Javascript将数值加载到2位小数。 除了299.90英镑和499.90英镑之外,所有价值似乎还可以,价格为299.9英镑和499.9英镑。

当前代码:

//ROUNDING FUNCTION
function round(num, decimals) {
     return Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals);
}

//LOADING VALUES - Line cost variable is £49.99/£29.99 * 10
jQuery(".content").html("£" + round(lineCost, 2));

我尝试过的:

jQuery(".content").html(parseFloat(lineCost * 100) / 100).toFixed(2);

jQuery(".content").html(Number(lineCost).toFixed(2));

有任何想法吗?

谢谢。

您可以在float / integer数值上尝试使用toFixed方法:

var value = 0.127456;
    value.toFixed(2);

输出:

0.13

在你的情况下:

jQuery(".content").html("£" + lineCost.toFixed(2));

如果lineCost是一个字符串,则将其解析为float:

jQuery(".content").html("£" + parseFloat(lineCost).toFixed(2));

你太复杂了。

它只需要

parseFloat(lineCost).toFixed(2);

这是一个演示小提琴

实际上舍入意味着将10.51112.49类的数字转换为12所以如果你想使用带小数的float ,你不应该舍入数字,而应该使用这样的东西:

var lineCost = 12.5;
parseFloat(lineCost).toFixed(2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM