Re: help with float numbers
| From: | Richard Lynch | Date: | Sun, 11 May 2003 00:26:06 +0000 |
| Subject: | Re: help with float numbers | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-147173@lists.php.net to get a copy of this message | ||
pdmytrew@lexmark.com wrote:
> I have quite a frustrating problem that I *think* involves floating-point
> ('double') numbers. I have the following code:
Yes.
Internally they are represented by "chopped off" decimals with, like,
lots of digits, but not infinite.
So 1/3 will never be exactly 1/3.
Perhaps suprisingly, 1/2 will most likely never be 1/2 either, because
the internal representation is, well, it's a bit complicated to go into,
but just assume that ALL fractions are infinitely repeating when they
turn into decimals and they get rounded off a bit.
> $Total = array_sum($Activity);
> if ($Total == 100) {
>
> // do some stuff
>
> } else {
> $Message = "Total is $Total! Please check your numbers.\n";
> }
>
> If $Activity has values like (25 , 25 , 25 , 25), then it works just fine.
> But if $Activity is an array of the following: (71.8 , 5.6 , 5.6 , 8.5 , 8.5)
> I get the message "Total is 100! Please check your numbers."
> I don't understand!!!
> If Total is 100, then why doesn't that meet the condition of the first if-statement ?!
> I suspect it has something to do with the way PHP deals with integers vs. floating-point
> numbers. Yes?
> For my purposes, $Activity may have all integers, all decimals, or a combination of both like
> (25, 25, 25, 12.5, 12.5).
> I'm using PHP 4.3.1. What can I do to allow for this? How do I compare an integer (100) to
> what MAY OR MAY NOT be a float ($Total)?
Are you simply checking that the total percentages add up to 100?
Perhaps it would be sufficient to say:
$Total = round(array_sum($Activity));
Or, perhaps you could even get away with:
if ($Total > 99 and $Total < 101){
Or...
It *REALLY* depends on your application and *WHY* you need this, rather
than having some cut-and-dried answer.
You may even need to be 100% (pun intended) accurate and dive into BC
MATH http://php.net/bc
Or not.
Just depends what you are trying to do.