PHP round() bug?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • db_guy

    PHP round() bug?

    <?
    $a=1.5345493;

    $b=round($a,2);

    echo "b: ".$b;
    ?>

    This code should return "b: 1.54", but instead returns "b: 1.53". Can
    anyone else confirm this?

    Also, does anyone have a way around this issue?

    PHP 4.3.6
    Apache 1.3.33
    MySQL 3.23.49

  • Chris Hope

    #2
    Re: PHP round() bug?

    db_guy wrote:
    [color=blue]
    > <?
    > $a=1.5345493;
    >
    > $b=round($a,2);
    >
    > echo "b: ".$b;
    > ?>
    >
    > This code should return "b: 1.54", but instead returns "b: 1.53". Can
    > anyone else confirm this?
    >
    > Also, does anyone have a way around this issue?[/color]

    Why should it return 1.54?

    1.5345493 rounded to two decimal places *should* give 1.53

    The numbers 0 to 4 are rounded down, and 5 to 9 are rounded up.

    The third number after the decimal place is a 4 which would indicate the
    number should be rounded down, leaving you with 1.53.

    --
    Chris Hope | www.electrictoolbox.com | www.linuxcdmall.com

    Comment

    • Gordon Burditt

      #3
      Re: PHP round() bug?

      ><?[color=blue]
      > $a=1.5345493;
      > $b=round($a,2);
      > echo "b: ".$b;
      >?>
      >
      >This code should return "b: 1.54",[/color]

      Would you care to justify that statement? WHY should
      it return 1.54?
      [color=blue]
      >but instead returns "b: 1.53". Can[/color]

      Which I believe to be the correct answer.[color=blue]
      >anyone else confirm this?
      >
      >Also, does anyone have a way around this issue?
      >
      >PHP 4.3.6
      >Apache 1.3.33
      >MySQL 3.23.49[/color]

      Gordon L. Burditt

      Comment

      • Anonymous

        #4
        Re: PHP round() bug?

        db_guy wrote:[color=blue]
        >
        > <?
        > $a=1.5345493;
        >
        > $b=round($a,2);
        >
        > echo "b: ".$b;
        > ?>
        >
        > This code should return "b: 1.54", but instead returns "b: 1.53". Can
        > anyone else confirm this?
        >
        > Also, does anyone have a way around this issue?[/color]

        Since 1.534... is smaller than 1.535, round($a,2) will correctly round
        it down to 1.53. I wouldn't know what should be wrong with that.

        Check the rounding functions. There are also functions that always round
        up or down, namely ceil() and floor(). Maybe you were looking for ceil()
        instead of round()?

        Comment

        Working...