Simple price cacluation, but I don't understand

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;
}

Maybe intended as a safeguard for the floating point arithmetic. Or for the correct rounding.

lack of knowledge?

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.

1 Like

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.

1 Like

That’s probably the reason right there.

Still trying to figure out what that modulo 10 is all about.

to get the remainder of cents / 10 i.e. 0.01 … 0.09

1 Like

the /10 is cents, but what is the %10 about?

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.

1 Like

Thank you, everyone.

I finally understand from top to bottom (including some things I never mentioned).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.