php - why does this happen?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cj-design
    Confirmed User
    • Apr 2003
    • 378

    #1

    php - why does this happen?

    PHP Code:
    $rrp = "19.99";
    $price = "14.99";
    $saving = $rrp - $price;
    $adding = $rrp + $price;
    
    print "RRP: $rrp";
    print "<p>";
    print "Price: $price";
    print "<P>";
    print "Saving $saving";
    print "<P>";
    print "Added Together $adding"; 
    
    Output:

    RRP: 19.99
    Price: 14.99

    Saving 5

    Added Together 34.98


    What happened to the decimal places on the saving?
  • cezam
    Confirmed User
    • Jun 2003
    • 1363

    #2
    it's 5.00, so print strips the decimal places off.

    printf is your friend, check manual.

    Comment

    • jovigirl
      Confirmed User
      • Apr 2003
      • 1796

      #3
      i dont wanna buy zoom glasses
      ICQ :333-548-380

      Comment

      • Brujah
        Beer Money Baron
        • Jan 2001
        • 22157

        #4
        it doesn't keep the format, you can use sprintf to do it.. instead of print.

        $saving = sprintf( "%01.2f", $rrp - $price );

        http://www.php.net/sprintf

        Comment

        • rowan
          Too lazy to set a custom title
          • Mar 2002
          • 17393

          #5
          Be careful using decimal places for pricing, you can get some strange effects with floats... probably better to calculate everything in cents internally (as a whole number), and then divide it by 100 to display it.

          Comment

          • cj-design
            Confirmed User
            • Apr 2003
            • 378

            #6
            cheers boys.

            Comment

            • Thorin
              Registered User
              • May 2002
              • 44

              #7
              Originally posted by cj-design
              What happened to the decimal places on the saving?

              ...

              PHP/MySQL Programmer

              Wow...

              Comment

              • Freestyleman
                Confirmed User
                • Sep 2002
                • 283

                #8
                Originally posted by Thorin



                Wow...

                Comment

                • JamesK
                  hi
                  • Jun 2002
                  • 16731

                  #9
                  Originally posted by jovigirl
                  i dont wanna buy zoom glasses
                  HAHAHAHAAHAHHA
                  M3Server - NATS Hosting

                  Comment

                  Working...