Problem with sum of decimal numbers


#1

Hi, I have a problem with the sum of two decimal numbers in javascript. In some case, if I execute the expression :

parseFloat(NUM_1) + parseFloat(NUM_2)

The sum modifies the result value adding some decimal digits not present in the original numbers.

For example

parseFloat(“1.1”) + parseFloat(“22.14”)
Or simply: 1.1+22.14
The result is : 23.240000000000002

I searched in google and I saw that this is a common problem and a possible solution is to use BigNumber. Is possible to use it in C3? If yes, how? If not, have you an alternative solution to solve this kind of problem?


#2

This is the default behavior of float numbers in any language not just javascript.
If you want precisions then you can use Decimal

c3ShowFunc(Decimal)

This type is usually used for accounting,

 type Bill {
  total:    decimal
  ...
}

#3

Ok but how can I do to convert the 2 numbers, before the sum, into Decimal ? Doesn’t exists a fuction like parseFloat to have a decimal in output? The problem is not the definition of the single number but the result of the sum.


#4
Decimal.make({value: parseFloat('1.1')}) + Decimal.make({value: parseFloat('22.14')})

however from console I still get 23.240000000000002 !!


#5

The following works by rounding to 2 decimal places:

(1.1+22.14).toFixed(2)
"23.24"

It returns a string, so you might have to use parseFloat() around, depending on what you want to do with the result…


#6

I am getting a similar issue using window expression function


#7

This has to do with the precision of floating point arithmetic. Checkout the article below

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html


#8

Something like this might help: https://www.thusspakeak.com/ak/2013/07/01-YoureGoingToHaveToThink02.html (fixed-point library).
Or this: https://github.com/MikeMcl/decimal.js/