PHP Round Up to Nearest 5 Cents

PHP is a great language to learn. Though it is easy to learn, sometime there are times where we will be stuck at a certain question as to how to solve an equation. In a business solution area, businesses tend to round up the value of their payment to nearest 5 cents.  Such example would be as below.

PHP Logo

Have a look at the below example :

$5.36 rounds up to nearest 5 cents : $5.40
$5.34 rounds up to nearest 5 cents : $5.35

You get the drill.

Below is the method that was specially written by me. As always float values in PHP has an issue regarding the truncation thus where you can read more about this HERE, though the function below will be able to help mitigate this problem.

What it does?

  1. Convert values into string after rounded to decimals.
  2. Then check value after decimal point to see location of the last number in the decimal.
  3. Check if value is 1 to 5 to display 5 and 6 to 9 to display 0.
  4. Display new value
/*
 *  Only call this function after already rounded to 2 decimals
 *  Function written by Daniel Chew - https://techiedan.com
 */
function roundUpTo5Cents($value) {

$valueInString = strval(round($value,2));
if (strpos($valueInString, ".") == 0) $valueInString = $valueInString.".00";
$valueArray = explode(".", $valueInString);
$substringValue = substr($valueArray[1], 1);

if ($substringValue >= 1 && $substringValue <= 5) {
$tempValue = str_replace(substr($valueArray[1], 1), 5, substr($valueArray[1], 1));
$tempValue = substr($valueArray[1],0,1).$tempValue;
$newvalue = floatval($valueArray[0].".".$tempValue);
} elseif($substringValue == 0) {
$newvalue = floatval($value);
} else {
$newFloat = floatval($valueArray[0].".".substr($valueArray[1],0,1));
$newvalue = ($newFloat+0.1);
}

return $newvalue;
}

If you have another perfect example, do assist other readers here.

3 Comments

  1. unex October 10, 2016
    • cocl February 1, 2017
      • techieDan May 29, 2017

Leave a Reply to cocl Cancel reply