3 ms·
Working in cents isn't always sufficient. Let's do 34.7% of $25. In cents, $25 is 2500. 34.7% of that is exactly 867.5 cents, which should round to 868 cents un
by tzs 7y ago
Working in cents isn't always sufficient. Let's do 34.7% of $25. In cents, $25 is 2500. 34.7% of that is exactly 867.5 cents, which should round to 868 cents under the most common rounding methods in most commercial applications (round to nearest with 0.5 rounding up, or round to nearest, with 0.5 rounding to even).
In JavaScript:
> p=2500; r=0.347;
< 0.347
> Math.round(p*r)
< 867
You need to integerize the percentage, too. For my current financial applications, all the percentages I need are integer multiple of 0.01%, so I use that as my "percent cent". 34.7% is then represented as 3470.
That leads to a function something like this (assuming you need the 0.5 round up rule...changing it to 0.5 rounds to even is left as an exercise):
function percent(amt2, rate4)
{
return Math.floor((amt2 * rate4 + 5000)/10000)
}
(The 2 and 4 suffixes are a naming convention I use. They are reminders that amt2 is the underlying amount x 100, and that rate4 is the underlying rate x 10000).