3

Can anyone explain the below output in PHP?

$num1 = (1.65 - 1.00);
echo "<br><br>num1 = " . $num1;   // Output: int = 0.65

$num_int1 = $num1 * 100;
echo "<br><br>int = " . $num_int1;   // Output: int = 65

$num_int2 = (int) $num_int1;
echo "<br><br>int = " . $num_int2;   // Output: int = 64

Why $num_int2 is 64?

Thanks for help.

1 Answer 1

15

From an article I wrote for Authorize.Net (in your specific case $num_int1 is a float even if it looks like an integer):

One plus one equals two, right? How about .2 plus 1.4 times 10? That equals 16, right? Not if you're doing the math with PHP (or most other programming languages):

echo floor((0.2 + 1.4) * 10); // Should be 16. But it's 15!

This is due to how floating point numbers are handled internally. They are represented with a fixed number of decimal places and can result in numbers that do not add up quite like you expect. Internally our .2 plus 1.4 times 10 example computes to roughly 15.9999999998 or so. This kind of math is fine when working with numbers that do not have to be precise like percentages. But when working with money precision matters as a penny or a dollar missing here or there adds up quickly and no one likes being on the short end of any missing money.

The BC Math Solution

Fortunately PHP offers the BC Math extension which is "for arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings." In other words, you can do precise math with monetary values using this extension. The BC Math extension contains functions that allow you to perform the most common operations with precision including addition, subtraction, multiplication, and division.

A Better Example

Here's the same example as above but using the bcadd() function to do the math for us. It takes three parameters. The first two are the values we wish to add and the third is the number of decimal places we wish to be precise to. Since we're working with money we'll set the precision to be two decimal palces.

echo floor(bcadd('0.2', '1.4', 2) * 10); // It's 16 like we would expect it to be.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks John. I was trying to work this out since 1 hour but couldn't do it. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.