0

I am making a service price tracker bot which will show something like this on price decrease:

Service price decreased from 0.10 to 0.05

If you buy right now, you could save <x>

<x> is the substracted amount or safe amount (oldPrice - newPrice).

Code for subtraction:

oldPrice - newPrice
0.10 - 0.05
// -> 0.05

While this works completely fine, but in some cases, if the service price (new or old) is like in more than 3 decimals e.g. 0.2184

The code will return weird full long number.

Examples:

0.2184 - 0.1404
// -> 0.07800000000000001
0.09 - 0.085
// -> 0.0049999999999999906
2.159 - 2.0088
// -> 0.1501999999999999

/* Rare cases */
0.1764 - 0.1134
// -> 0.063
5.675 - 2.275
// -> 3.4
5.175 - 1.775
// -> 3.4

I obviously tried things like Math.abs() and use String.replace() to remove 00 and 99, but nothing really works.

e.g.

2.159 - 2.0088
// -> 0.1501999999999999

String(2.159 - 2.0088).replace(/[09][09]+/g, "");
// -> "0.1501"

0.2184 - 0.1404
// -> 0.07800000000000001

String(0.2184 - 0.1404).replace(/[09][09]+/g, "");
// -> "0.0781"
// -> Right: "0.780"
// -> Mistakes: 0.0 and 781 instead of 780

Note: I don't really care if the result is in string.

As you already saw above, it calculates wrong or essentially removes the main 9s or 0s.

Is there any other approach or it's the best one?

  • 1
    This is an issue with floating point numbers. It comes up in all programming languages and all operating systems. I would recommend you search github for a solution that fits your requirements: https://www.google.com/search?q=github+enhanced+floating+point+number+calculation – ControlAltDel Apr 13 '22 at 17:59

1 Answers1

0

Treat the numbers as integers, then divide:

(2184 - 1404)/10000 // -> .078

Lauren Prete
  • 142
  • 4