I see this code in several sales tax calculators for creating the final price format:
function fmtPrice(value)
{
result="$"+Math.floor(value)+".";
var cents=100*(value-Math.floor(value))+0.5;
result += Math.floor(cents / 10);
result += Math.floor(cents % 10);
return result;
}
Basically, what I don’t understand is what is going on with the cents at all beginning here:
var cents=100*(value-Math.floor(value))+0.5;
So, it rounds down the value, subtracts the value, multiplies the value by 100 and then adds .5 to get cents? WHA???
But, then it divides by 10 and performs a modulo 10 to finish up the deal:
result += Math.floor(cents / 10);
result += Math.floor(cents % 10);
Makes no sense to me at all…
Why wouldn’t you just do this instead???
function fmtPrice(value) {
result = "$" + value.toFixed(2);
return result;
}
Okay, but it’s in a lot of calculators I can Google up and I don’t even comprehend how it functions. It seems like if they were arriving at a solution due to lack of knowledge it would be much easier to discover the toFixed() method than to come up with this rigamarole.
EDIT: maybe I’m starting to understand the logic finally. Holy crud is it mind-bending.
A lot of the time people just google for a solution and don’t think any further than that. So you can copy yourself quite a long time even if there is a native solution.
toFixed(2) might not round off the way the tax should be calculated. For example, 3.255.toFixed(2) will give you “3.25” but 3.245.toFixed(2) will also give you “3.25”. If the digit before the final 5 is odd, it rounds down, but if the digit before the final 5 is even, it rounds up.
Maybe with taxes, the number is always rounded up.
Take two examples: 16.4753 and 16.4235. After you take the cents and add 0.5, you get 48.03 and 42.85. You want to end up with 48, and 42 for the cents. In Math.floor(cents % 10), the cents%10 gives you 8.03 and 2.85. Then you need to isolate the first digit using Math.floor.