Javascript toFixed不舍入 [英] Javascript toFixed Not Rounding

查看:140
本文介绍了Javascript toFixed不舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用javascript绑定到一些复选框, toFixed(2)没有四舍五入。任何想法为什么它不四舍五入?例如,如果数字是 859.385 ,它只显示 859.38 而不是 859.39

I'm using javascript to bind to some checkboxes, and the toFixed(2) is not rounding up. Any ideas why it's not rounding? For instance, if the number is 859.385 it's only displaying 859.38 instead of 859.39.

我还读到 toFixed 可以根据您使用的浏览器进行不同的循环,任何人都知道解决这个问题,以便我的javascript计算与我的php计算相匹配?

I've also read that the toFixed can round differently depending on which browser you are using, anyone know of a way around this so that my javascript calculations match my php calculations?

var standardprice = parseFloat($('#hsprice_'+this.id.split('_')[1]).val());
var price =  parseFloat($('#hprice_'+this.id.split('_')[1]).val());
var discount =  parseFloat($('#hdiscount_'+this.id.split('_')[1]).val());
var deposit =  parseFloat($('#hdeposit_'+this.id.split('_')[1]).val());

var currSprice = parseFloat($('#hTotalSprice').val());
var currPrice = parseFloat($('#hTotalPrice').val());
var currDiscount = parseFloat($('#hTotalDiscount').val());
var currDeposit = parseFloat($('#hTotalDeposit').val());

currSprice += standardprice;
currPrice += price;
currDiscount += discount;
currDeposit += deposit;

$('#lblTotalSprice').text('$'+addCommas(currSprice.toFixed(2)));
$('#lblTotalPrice').text('$'+addCommas(currPrice.toFixed(2)));
$('#lblTotalDiscount').text('$'+addCommas(currDiscount.toFixed(2)));
$('#lblTotalDeposit').text('$'+addCommas(currDeposit.toFixed(2)));

$('#hTotalSprice').val(currSprice.toFixed(2));
$('#hTotalPrice').val(currPrice.toFixed(2));
$('#hTotalDiscount').val(currDiscount.toFixed(2));
$('#hTotalDeposit').val(currDeposit.toFixed(2));


推荐答案


我还没有找到toFixed10错误的数字。其他人可以吗?

I have yet to find a number that toFixed10 does wrong. Can anybody else?

感谢 blg 他的答案,它指向了Mozilla的 toFixed10()方法。

Thanks to blg and his answer which pointed me to Mozilla's toFixed10() method.

使用它我想出了这个简短的衬垫,这确实涵盖了这里提到的所有情况......

Using that I came up with this short one liner, which indeed covers all cases mentioned here...

function toFixed( num, precision ) {
    return (+(Math.round(+(num + 'e' + precision)) + 'e' + -precision)).toFixed(precision);
}

这篇关于Javascript toFixed不舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆