简体   繁体   English

JavaScript 方法 toFixed(2) 给出了一个意外的值

[英]JavaScript method toFixed(2) gives an unexpected value

I have a calculation problem with.toFixed(2) and hope that anybody can give me an alternative way or idea.我对 .toFixed(2) 有一个计算问题,希望任何人都可以给我另一种方法或想法。 The calculation is based for german social insurance contributions.该计算基于德国社会保险缴款。 I have a gross of 3700. This amount has to be multiplied with 1.525% and finally the amount rounded to two decimal numbers.我总共有 3700。这个数额必须乘以 1.525%,最后四舍五入到两位小数。 Here is my code:这是我的代码:

var _PVGross = 3700;
var _charge = 1.525;
result = ((_PVGross / 100) * _charge).toFixed(2);

the calculation handmade is:手工计算是:

3700 / 100 = 37 3700 / 100 = 37

37 * 1.525 = 56.425 37 * 1.525 = 56.425

So, the code above returns me 56.42.因此,上面的代码返回 56.42。 But in the german law it has to be 56.43 because of the third digit is a five.但在德国法律中,它必须是 56.43,因为第三个数字是 5。 This means round up.这意味着四舍五入。 I tried several manual tests with https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tofixed2 but every time if there are only three digits or zeros behind the dot I will get the wrong result.我用https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tofixed2尝试了几次手动测试,但每次如果点后面只有三个数字或零,我都会得到错误的结果。

Another example:另一个例子:

if I have this amount/code:如果我有这个数量/代码:

56.42500000001.toFixed(2)

the result will be 56.43.结果将是 56.43。 And now I am running out of ideas.现在我的想法已经不多了。 I am using google Apps Script for this calculation.我正在使用 google Apps Script 进行此计算。 Anybody else with this problem and/or ideas?还有其他人有这个问题和/或想法吗?

Have you tried something like this Math.round((56.425 + Number.EPSILON) * 100) / 100 ?你有没有试过这样的东西Math.round((56.425 + Number.EPSILON) * 100) / 100

You can round it up, by using Math.pow您可以使用 Math.pow 将其四舍五入

var _PVGross = 3700;
var _charge = 1.525;
var res = 56.425;
result= Math.round(res * 100) / 100);

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

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