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 9
s or 0
s.
Is there any other approach or it's the best one?