We are excited to announce that the ASP.NET Forums are moving to the new Microsoft Q&A experience. Learn more >

## 4 replies

Last post Mar 04, 2021 10:28 PM by PaulTheSmith

• joegreen2005

Member

61 Points

460 Posts

### JavaScript Decimal Math

Hello,

When I do 34.09 * 11, I get 374.99 but if I add 340.91 and 34.09 in JavaScript, I get 375.00 instead of 374.99.  Here is my code:

`<p id="demo"></p>`
```var num = (parseFloat(340.90) + parseFloat(34.09));
num = parseFloat(num).toFixed(2);
document.getElementById("demo").innerHTML = n;
```

Why JavaScript is rounding 374.99 to 375. What do I need to do to get 374.99?

Joe

• mgebhard

All-Star

53711 Points

24038 Posts

### Re: JavaScript Decimal Math

#### joegreen2005

Hello,

When I do 34.09 * 11, I get 374.99 but if I add 340.91 and 34.09 in JavaScript, I get 375.00 instead of 374.99.  Here is my code:

`<p id="demo"></p>`
```var num = (parseFloat(340.91) + parseFloat(34.09));
num = parseFloat(num).toFixed(2);
document.getElementById("demo").innerHTML = n;```

Why JavaScript is rounding 374.99 to 375. What do I need to do to get 374.99?

Joe

`340.91 + 34.09  = 375`

Maybe you mean

`340.91 + 34.08 = 374.99`

Plus your code has a bug.

• joegreen2005

Member

61 Points

460 Posts

### Re: JavaScript Decimal Math

The error is happening when I add 34.09 + 34.09 + 34.09 + 34.09 + 34.09,  I get 170.455 and when I do 170.455.toFixed(2) I get 170.46 which should be 170.45 and not 170.46.

• bruce (sqlwo...

All-Star

58474 Points

15790 Posts

### Re: JavaScript Decimal Math

Mar 04, 2021 09:22 PM|bruce (sqlwork.com)|LINK

javascript does not do decimal arithmetic. all numbers are 64 bit floats. floats (because they are binary rather than decimal) can not be used for money, as you will get precision errors. this is usually covered in comp sci 101, so I assume you don't have a formal edition in computer science.

just like 1/3 is .33333.. in decimal, several decimal number are repeating binaries.   see:

the typical solution to calculating money with floats is to use a fixed precision library (like C# money) or do all the calculations in pennies (or mills if more precision required) and divide by 100 (or 1000 if mills)

> (3409 + 3409 + 3409 + 3409 + 3409) / 100
< 170.45

you can do a simple javascript math package:

```const pennyMath = {
toPenny: (d) => Math.round(d * 100),
add: (d1,d2) => (pennyMath.toPenny(d1) + pennyMath.toPenny(d2)) / 100,
sub: (d1,d2) => (pennyMath.toPenny(d1) - pennyMath.toPenny(d2)) / 100,
mul: (d1,d2) => Math.round(pennyMath.toPenny(d1) * pennyMath.toPenny(d2)) / 100,
div: (d1,d2) => Math.round(pennyMath.toPenny(d1) / pennyMath.toPenny(d2)) / 100,
sum: (...d) => d.reduce((a,c) => pennyMath.toPenny(c) + a,0) / 100
};```

then:

pennyMath.sum(34.09 , 34.09 , 34.09 , 34.09 , 34.09)

gives 170.45

bruce (sqlwork.com)
• PaulTheSmith

Participant

1660 Points

952 Posts