DEV Community

[Comment from a deleted post]
Collapse
 
orientlion profile image
orientlion

Cool^^ Btw, it calculates a 2.91$ tip for a 29$ bill. Wondered the math behind it (ceil function, floating division etc.)

Collapse
 
erdn0 profile image
erdn0

there is a mathFormat() function with ceil in it but if there is a problem/ mistake I would like to know because im a beginner

Collapse
 
orientlion profile image
orientlion • Edited

Hey. Sorry if I was not clear. Just that I tried some numbers and some of them gives results like this
Bill: 29$ | Select Tip: %10 | Tip: 2.91$
Bill: 34$ | Select Tip: %10 | Tip: 3.41$
or:
Bill: 32$ | Select Tip: %10 | Tip: 3.20$ | Total: 35.21$

see the 0.01$s? like 2.91$ tip while I assume it should be like 2.90$. I think that might be caused by some fluctuating number operations if js is similar to java with that respect.
I meant that.
I think your tip calculator looks great by the way. Very cool^^

 
erdn0 profile image
erdn0

function formatMoney(value) {
value = Math.ceil(value * 100) / 100;
value = value.toFixed(2);
return value;
}
maybe it comes from here?
this was used in the tutorial , sometimes the result could be very long because of decimals.

 
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^^