Instantly share code, notes, and snippets.

# kkyucon/arithmetic.md

Last active August 28, 2020 03:30
Show Gist options
• Save kkyucon/af49ccfcf358430952ec50614f5a9744 to your computer and use it in GitHub Desktop.
PHP Percentage and Rounding

# PHP Percentage and Rounding

Rounding a tax result, we have a tax of 9.975%:
`\$tax=.09975;`

And we have an amount of 100:
`\$amount=100;`

Let's calculate the value of this percentage towards the value of the amount, so:
`\$tx=\$amount*\$tax;`

Above, the result would be`\$tx` is equal to`\$amount`(100) multiplied(`*`) by `\$tax`(0.09975) which would give a result of`\$tx` is equal to 9.975%.

If we were doing a true mathematical equation then `\$tx` would be our final result.

But let's say that we needed a value for a customer receipt. So we would first round that value to 2 decimal points:
`\$t = round(\$tx, 2);`

In the above`\$t` is equal to`\$tx` rounded to 2 decimal points. So`\$t` is equal to 9.97.

This is all too easy. But in the real world of accounting, we round-up last digit equal(=) or greater(>) then 5 and round-down on 4. So the following code would correct this. We will change`\$amount`equal to 150 just to get a better understanding:

```<?php
//This is our price
\$amount=150;
//This is our tax% rendered to a decimal value /100
\$tx=0.09975;
//\$txc= 150 x 0.09975
\$txc=\$amount*\$tx;
//Below is output to document, will print 14.9625
echo \$txc;
//\$tax= taking 3rd integer at 5 and above from decimal and round-up to 0
\$tax=round(\$txc,3,PHP_ROUND_HALF_UP);
//Output is 14.963
echo \$tax;
//Here we take \$tax and format it's value to 2 digits after decimal
//And this is why we don't need to use PHP_ROUND_HALF_DOWN, as it already will be
\$t= number_format(\$tax, 2);
//Output is 14.96
echo \$t;
?>```

The output of the above code in our document will be:

``````14.9625
14.963
14.96
``````

Let's go a step further and add the tax to the price for our grand total. Just add these lines to the code:

```\$total=\$amount+\$t;
echo \$total;```

Our final output:

``````14.9625
14.963
14.96
164.96
``````

Bet we thought algebra would not come in handy? As we can see there are similarities.

Now that we are well off with the basics of percentage, decimal and rounding, we also have a fair understanding of arithmetic as well. So we can use divisions(/) and subtractions(-) in our PHP code instead of, or in addition to.