André Herb
André Herb

Reputation: 1

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. 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. Here is my code:

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

the calculation handmade is:

3700 / 100 = 37

37 * 1.525 = 56.425

So, the code above returns me 56.42. But in the german law it has to be 56.43 because of the third digit is a five. 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.

Another example:

if I have this amount/code:

56.42500000001.toFixed(2)

the result will be 56.43. And now I am running out of ideas. I am using google Apps Script for this calculation. Anybody else with this problem and/or ideas?

Upvotes: 0

Views: 74

Answers (2)

JimiA
JimiA

Reputation: 87

You can round it up, by using Math.pow

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

Upvotes: 1

Zurez
Zurez

Reputation: 191

Have you tried something like this Math.round((56.425 + Number.EPSILON) * 100) / 100 ?

Upvotes: 2

Related Questions