Connecting Tech Pros Worldwide Help | Site Map

Rounding problem

laredotornado@zipmail.com
Guest
 
Posts: n/a
#1: Mar 24 '08
Hi,

I'm using PHP 4.4.4. I'm confused about the function "round". I have

<?= "prov tax: $provincial_tax " . round($provincial_tax, 2) . "<BR>
\n" ?>

When $provincial_tax = 7.185, the output above is

prov tax: 7.185 7.18

Shouldn't the second number be 7.19 since 7.185 rounds to 7.19? I
appreciate any insights you may have, - Dave
PaulB
Guest
 
Posts: n/a
#2: Mar 24 '08

re: Rounding problem


laredotornado@zipmail.com wrote:
Quote:
Hi,
>
I'm using PHP 4.4.4. I'm confused about the function "round". I have
>
<?= "prov tax: $provincial_tax " . round($provincial_tax, 2) . "<BR>
\n" ?>
>
When $provincial_tax = 7.185, the output above is
>
prov tax: 7.185 7.18
>
Shouldn't the second number be 7.19 since 7.185 rounds to 7.19? I
appreciate any insights you may have, - Dave
<?php
$provincial_tax = 7.185;
$provtax = round($provincial_tax, 2);
echo $provtax;
?>

I ran that in DzSoft PHP Editor 4.1.2. and it gave me 7.19, then I ran it on
my server running PHP version 5.2.5 and it gave 7.19 so what's the problem?
Maybe it's the PHP version.

Paul
--
Add an underscore after the p to reply


Jerry Stuckle
Guest
 
Posts: n/a
#3: Mar 24 '08

re: Rounding problem


laredotornado@zipmail.com wrote:
Quote:
Hi,
>
I'm using PHP 4.4.4. I'm confused about the function "round". I have
>
<?= "prov tax: $provincial_tax " . round($provincial_tax, 2) . "<BR>
\n" ?>
>
When $provincial_tax = 7.185, the output above is
>
prov tax: 7.185 7.18
>
Shouldn't the second number be 7.19 since 7.185 rounds to 7.19? I
appreciate any insights you may have, - Dave
This has been discussed many times in this forum, and it has to do with
the internal representation of floating point numbers in the hardware.
7.185 is a repeating decimal (like 1/3 is in decimal) and cannot be
represented exactly.

The value is probably not 7.185, but something like 7.184999999345.
Printed, it shows 7.185. But rounding will take it to 7.184, which is
correct. If you want to round to 7.185, you have to add a fudge factor,
i.e.
round($provincial_tax + 0.0001);

Or do everything using integers and only change it when you go to display.



--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================
The Natural Philosopher
Guest
 
Posts: n/a
#4: Mar 25 '08

re: Rounding problem


laredotornado@zipmail.com wrote:
Quote:
Hi,
>
I'm using PHP 4.4.4. I'm confused about the function "round". I have
>
<?= "prov tax: $provincial_tax " . round($provincial_tax, 2) . "<BR>
\n" ?>
>
When $provincial_tax = 7.185, the output above is
>
prov tax: 7.185 7.18
>
Shouldn't the second number be 7.19 since 7.185 rounds to 7.19? I
appreciate any insights you may have, - Dave
7.185 does not 'round' either way..its a 50-50 choice to round it up or
down.
Closed Thread


Similar PHP bytes