javascript正确舍入到两位小数,不可能?

Bob*_*Bob 10 javascript currency rounding

在PHP中,我们有number_format().传递给它的值如下:

number_format(3.00 * 0.175, 2);
Run Code Online (Sandbox Code Playgroud)

返回0.53,这是我所期望的.

但是,在JavaScript中使用 toFixed()

var num = 3.00 * 0.175;
num.toFixed(2);
Run Code Online (Sandbox Code Playgroud)

返回0.52.

好吧,也许toFixed不是我想要的......也许是这样的......

var num = 3.17 * 0.175;
var dec = 2;
Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
Run Code Online (Sandbox Code Playgroud)

不,这也不起作用.它将返回0.56.

如何number_format在JavaScript中获得一个不能给出错误答案的函数?

实际上我确实为js找到了number_format的实现,http://phpjs.org/functions/number_format ,但它遇到了同样的问题.

这里有什么用JavaScript四舍五入?我错过了什么?

Dan*_*eam 13

JavaScript在浮点数方面做得很糟糕(与许多其他语言一样).

我跑的时候

3.000 * 0.175
Run Code Online (Sandbox Code Playgroud)

在我的浏览器中,我得到了

0.5249999999999999
Run Code Online (Sandbox Code Playgroud)

哪个不会达到0.525 Math.round.为了避免这种情况,你必须将双方都加倍,直到你得到它们为整数(相对容易,知道一些技巧有帮助).

所以要做到这一点,我们可以这样说:

function money_multiply (a, b) {
    var log_10 = function (c) { return Math.log(c) / Math.log(10); },
        ten_e  = function (d) { return Math.pow(10, d); },
        pow_10 = -Math.floor(Math.min(log_10(a), log_10(b))) + 1;
    return ((a * ten_e(pow_10)) * (b * ten_e(pow_10))) / ten_e(pow_10 * 2);
}
Run Code Online (Sandbox Code Playgroud)

这可能看起来很时髦,但这里有一些伪代码:

get the lowest power of 10 of the arguments (with log(base 10))
add 1 to make positive powers of ten (covert to integers)
multiply
divide by conversion factor (to get original quantities)
Run Code Online (Sandbox Code Playgroud)

希望这是你正在寻找的.这是一个示例运行:

3.000 * 0.175
0.5249999999999999

money_multiply(3.000, 0.175);
0.525
Run Code Online (Sandbox Code Playgroud)