Mathematical Formulae

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

Open in new window


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?
LVL 2
rolandmyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ozoCommented:
Do you want round to 0.01 rather than round to 0.05?

function roundToPenny($value) {
    // multiply the value by 100
    $value *= 100;
    // round it off just to be safe
    $value = round($value);
    // divide by 100 to get back to a decimal amount
    $value /= 100;
    return $value;
  }
0
TommySzalapskiCommented:
round($value, 2)
will round to the nearest penny. That whole function is not needed since you are now doing normal rounding.
0
ozoCommented:
or just round($value,2)
0
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Cornelia YoderArtistCommented:
Why are you using that function when

number_format($variable, 2, '.', '')

already gives you what you want?

And if all you need is the value, not the formatting, just use round() as others have said.
0
rolandmyAuthor Commented:
You guys are almost there.

0.213333333333 gives me 0.21

I wanted 0.22 as the result.

Even if the value is 0.01123, I need the result to be 0.02 after applying the function or round.
0
ozoCommented:
If you want to round up, use ceil instead of round
0
Cornelia YoderArtistCommented:
I don't think ceil() will work because that result is always an integer.
0
ozoCommented:
ceil($value*100)/100
instead of
round($value*100)/100
0
Cornelia YoderArtistCommented:
You can always round up this way using ceil()

$out = ceil(($value*100))/100;
0
ozoCommented:
But note that 0.01 is not represented exactly in IEEE Standard 754 Floating-Point
so when you think you are passing it 0.07 you may really be passing it
0.070000000000000006661338147751
0
rolandmyAuthor Commented:
ceil(($value*100))/100; works to a certain extend.

Results:
0.0533333333333 gives me 0.06, which is what I wanted.

The problem is with other results generated, 0.72 gives me 0.73 and 0.24 gives me 0.25. These should stay at 0.72 or 0.24.

The other noticeable ones are 0.48 becomes 0.49, 0.56 becomes 0.57. Seem to be happening to results with 2 decimal places.

Some results are correct though, like 0.08 stays at 0.08
0
ozoCommented:
In  IEEE Standard 754 single precision Floating-Point the closest representable value to 0.72 is
.7200000286102294921875

If you need exact values, you should not be using floating point.
Can you work in pennies instead of pounds or dollars and use integers?
0
Peter KwanAnalyst ProgrammerCommented:
How about this way?

function roundToNickle($value) {
    $epsilon = 0.00001;

    // multiply the value by 100
    //    for some reason value%.05 gives a divide by zero error
    $value *= 100;
    // round it off just to be safe
    $value1 = round($value);
    $value2 = ceil($value);

    if (abs($value1 - $value) < $epsilon)
        $value = $value1;
    else
        $value = $value2;

    // divide by 100 to get back to a decimal amount
    $value /= 100;
    return $value;
  }

Open in new window

0
ozoCommented:
If you can guarantee, for example, that you will never need to distinguish between
0.72 and 0.720001
then you may be able to manage with something like

round($value*100+0.499999)/100

But that will also fail at some point.
For example, if you use single precision IEEE Standard 754 Floating-Point,
10000.720002 will be indistinguishable from 10000.72
If you know what you can guarantee in terms of how close a number can be without rounding up, and what the range of numbers you need to be able to handle, and the precision of the floating point numbers you are using, we may be able to suggest an appropriate threshold, but remember

“Floating point computation is by nature inexact, and programmers can easily misuse it so that the computed answers consist almost entirely of “noise.” One of the
principal problems of numerical analysis is to determine how accurate the results of
certain numerical methods will be. There is a “credibility-gap”: We don’t know how
much of the computer’s answers to believe. Novice computer users solve this problem
by implicitly trusting in the computer as an infallible authority; they tend to believe
that all digits of a printed answer are signi¿cant. Disillusioned computer users have
just the opposite approach; they are constantly afraid that their answers are almost
meaningless.”

See also
https://www.validlab.com/goldberg/paper.pdf
0
Cornelia YoderArtistCommented:
There are mathematical ways to fix this floating point problem, but ozo is absolutely correct that it is inherent in the use of floating point data.

You would need to decide at which decimal point you want to discard the rest.

If you round up .720034, then should you round up .72000000000000034?  How many zeroes are enough before you decide it is .72 rather than .73?
0
Ray PaseurCommented:
Notes about using float values in PHP (see the large red warning box):
http://php.net/manual/en/language.types.float.php

If you would like to get a tested and working code sample, please follow the guidance of the SSCCE.  In this case, if you can give us a list of the input values and the desired output values, we can show you the exact code to get from input to output.  Obviously the quality of the test data matters, so please feel free to throw in not only the mainstream, but also the edge cases when you make your list.
0
rolandmyAuthor Commented:
Erm. Refer to the list below for sample "live" values that I extracted from the database.

0.186666666667 becomes 0.19 <-- correct
0.08 becomes 0.08 <-- correct
0.106666666667 becomes 0.11 <-- correct
0.24 becomes 0.25 <-- wrong (should stay the same value)
0.48 becomes 0.49 <-- wrong (should stay the same value)
0.32 becomes 0.32 <-- correct
0
Cornelia YoderArtistCommented:
In your database, what is the data type of the values?

float?
double?
decimal?

What precision is specified for it?
0
Ray PaseurCommented:
Are you using DECIMAL data types in the data base table?  If so, the errors might arise in the PHP computations.  Did you pay much for that function roundToNickle()?

Please see line 64 in this example.

<?php // RAY_temp_rolandmy.php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28230040.html#a39463959
/* PROBLEM DEFINITION
0.186666666667 becomes 0.19 <-- correct
0.08 becomes 0.08 <-- correct
0.106666666667 becomes 0.11 <-- correct
0.24 becomes 0.25 <-- wrong (should stay the same value)
0.48 becomes 0.49 <-- wrong (should stay the same value)
0.32 becomes 0.32 <-- correct
*/

// FAILING FUNCTION
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;
}

// TEST DATA
$arr = array
( 0.186666666667
, 0.08
, 0.106666666667
, 0.24
, 0.48
, 0.32
)
;
var_dump($arr);

// TEST THE BAD FUNCTION (DOES NOT TEST TRUE TO POSTED EXAMPLE)
foreach ($arr as $num)
{
    echo PHP_EOL;
    echo $num;
    echo ' => ';
    echo roundToNickle($num);
}
echo PHP_EOL;

// SHOW THE RIGHT WAY
foreach ($arr as $num)
{
    echo PHP_EOL;
    echo $num;
    echo ' => ';
    echo number_format($num,2);
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rolandmyAuthor Commented:
Ray, you will forever remain as the hero of ee.

Now it goes back to my original problem (the main question).

As I mentioned in the question, I need to round up.

Data like 1.011 becomes 1.01. I need it to be 1.02

Or data like 0.21333 becomes 0.21 instead of 0.22


P.s. The roundtoNickle function was from an expert here. It suited my needs back then.
0
ozoCommented:
"Data like 1.011 becomes 1.01. I need it to be 1.02"
Should  1.0101 become  1.02?
Should  1.01001 become  1.02?
Should  1.010001 become  1.02?
At some point, if your numbers are represented as floats, there may be a problem defining where you draw the line between 1.01 and 1.02
Depending on how precisely you want to draw that line there may be trade offs we can make to do it with floats, or it may be impossible to do using floats.

for the particular values in your list:
0.186666666667 becomes 0.19 <-- correct
0.08 becomes 0.08 <-- correct
0.106666666667 becomes 0.11 <-- correct
0.24 becomes 0.25 <-- wrong (should stay the same value)
0.48 becomes 0.49 <-- wrong (should stay the same value)
0.32 becomes 0.32 <-- correct
Something like
round($value+.0049,2) may suffice, but there will be other values it will fail on, so unless there are values for which failure is acceptable (perhaps because you can guarantee that you will never see those values) we cannot guarantee a function that works in all cases.

Are you sure you can't work with integer penny values instead of float pound/dollar values?
0
Ray PaseurCommented:
my original problem (the main question).
To help you any further we need to see the SSCCE.  In this case that would be a set of input values and the expected outputs, along with the rules you want to apply to transform the inputs into the outputs.  A two column layout of the inputs and the corresponding expected outputs would suffice.  Please post that here, and I'll try to help you make sense of it.

However, please note that there are laws about handling money values, so if your rules violate the laws, you may expect a knock at the door.
0
rolandmyAuthor Commented:
Sorry for late reply. Long holiday over here. Going to accept multiple solutions.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.