DEV Community

[Comment from a deleted post]
 
orientlion profile image
orientlion

From my Java knowledge (hope it's relatable) I can assume that the code is written this way to round the decimal points to an upper level and format the result to a two decimal point number.
Like if the
Bill: 33.44$ | Select Tip: %10 | Tip: 3.35$
so the current code does:
33.44 --(%10)--> 3.344 --(ceil and toFixed)-> 3.35
which is great but I think the issue arises when the ceil is used on a number which does have a very long decimal part.

For example, if I were to take %10 of the number 29 by a multiplication operation, I would obtain the following result:
29 * 0.10 --> 2.9000000000000004 |not what we expected right?
this is a thing that happens in programming languages when using fluctuating numbers I believe (there are some technical explanations for this which I don't really know).

So the same code you have written and worked perfectly for most numbers does this when it comes to our unexpected 2.9.........04:
2.9000000000000004 ----(ceil and toFixed)--> 2.91
because of that 4 at far away, ceil function actually sees it and increases to the point where the number is 2.91 now.

So how to solve this?
I think you can do division instead of multiplication (if that's the case in your case) when taking the percentages of numbers. Like:
if your version to take %10 is like this: 29 * 0.10
you can convert that code to (29 * 10) / 100
which is basically the same thing in algebra.

another example, take the %11.8 of 29:
(29 * 11.8) / 100
///////////////////////////////////////////////
So bottom line I think taking percentages of numbers with the operation
(NUMBER * PERCENTAGE) / 100
instead of NUMBER * 0.PERCENTAGE
could fix this issue.

I'm sorry if this is misleading, anyone who nows JS can jump into the discussion^^