troubleshooting Question

Mathematical Formulae

Avatar of rolandmy
rolandmyFlag for Malaysia asked on
PHPAlgorithmsProgramming Theory
23 Comments5 Solutions386 ViewsLast Modified:
Dear experts,

I had this function in PHP provided by an expert previously.

function roundToNickle($value) {
    // multiply the value by 100
    //    for some reason value%.05 gives a divide by zero error
    $value *= 100;
    // get remainder of value / 5
    $remain = $value % 5;
    if ($remain < 2.5) {
      // round down by subtracting the remainder
      $value -= $remain;
    } else {
      // round up by adding difference between 5 and remainder
      $value += (5-$remain);
    }
    // round it off just to be safe
    $value = round($value);
    // divide by 100 to get back to a decimal amount
    $value /= 100;
    return $value;
  }

Usage is roundToNickle(number_format($variable, 2, '.', ''))

The result I got for say, 0.186666666667 is 0.2 which is not wrong for billing purpose. However, to calculate the actual cost, I need the result to be 0.19

Other results
0.213333333333 gives me 0.2 when I need it to be 0.22
0.0533333333333 gives me 0.5 when I need it to be 0.06

Any chance for experts to update the function?
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 5 Answers and 23 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 5 Answers and 23 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros