1

Probably this question is already existed somewhere but can't find my specific issue.

I have a two numbers that I want to add and I don't want to use round() function since I am working with money.

1.70 + 1.44 = 3.14 //Returns 3.1399999999999997
1.70 + 1.45 = 3.15 //Returns the correct answer
1.70 + 1.37 = 3.07 //Returns 3.0700000000000003

I tried it in Javascript but still the same issue.

Meydjer Luzzoli
  • 343
  • 2
  • 10
aldesabido
  • 1,268
  • 2
  • 17
  • 38

3 Answers3

1

Since you're working with money, always use the decimal.Decimal class in Python.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Use parseFloat to precision :

parseFloat(number).toFixed(precision);

E.g.

parseFloat(1.70 + 1.37).toFixed(2);  // RETURN 3.07
Joey Etamity
  • 856
  • 4
  • 9
0

one way you can achieve this is to multiply the values by (10 * precision) that you need and then divide the result by (10 * precision).

  • ((1.70 * 100) + (1.37 * 100))/100 = 3.07
  • ((1.70 * 100) + (1.45 * 100))/100 = 3.15
  • ((1.70 * 100) + (1.44 * 100))/100 = 3.14

you can add a method to do this for you to keep it simple.