舍入到小数点后两位

时间:2014-04-01 08:08:38

标签: javascript jquery rounding

我使用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));

有什么想法吗?

感谢。

3 个答案:

答案 0 :(得分:1)

您可以使用toFixed / floatinteger方法尝试:

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

输出:

0.13

在你的情况下:

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

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

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

答案 1 :(得分:1)

你过度复杂了。

只需要

parseFloat(lineCost).toFixed(2);

这是a demo fiddle

答案 2 :(得分:0)

实际上,舍入表示将10.51112.49之类的数字转换为12,因此如果您想使用{{1},则不应对该数字进行舍入使用小数,你应该使用这样的东西:

float