Weird PHP problem when multiplying

Discussion in 'PHP' started by Dakuipje, Apr 8, 2010.

  1. #1
    Ok so I never encountered this problem before and a google search didnt really help me either. Before going into the problem you should know I encountered this using a local Wamp server.

    I tried to multiply some simply numbers and somehow PHP automatically rounds the result to a full digit, while I need at least 2 digits.

    $total = $price * $ordered; 
    PHP:
    Price is 9,95 and ordered is 1.
    It outputs 9 as answer .....

    I allready tried this without success (same output):

    $total = round($price * $ordered, 2);
    PHP:

    Its also weird that it round it down instead of up. Maybe its a phpconfig issue ?

    Please help me !
     
    Dakuipje, Apr 8, 2010 IP
  2. Sergey Popov

    Sergey Popov Peon

    Messages:
    29
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Maybe you just need to replace comma with dot?

    I mean:
    
    $total = round(str_replace(',','.',$price) * $ordered, 2);
    
    PHP:
     
    Sergey Popov, Apr 8, 2010 IP
  3. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #3
    I dont use WAMP, but this must be part of your problem. If you cast them as floats, does this get around your issue?

    <?php
    (float) $price = 9.95;
    (float) $ordered = 1;
    
    (float) $total = $price * $ordered;
    
    print $total;
    ?>
    PHP:
     
    lukeg32, Apr 8, 2010 IP
  4. Dakuipje

    Dakuipje Peon

    Messages:
    931
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #4
    No im afraid the problem lies deeper then that. I tried that but without a good result.

    See when I simply echo the numbers from the database it also outputs them as: 9 instead of 9,95 while it is correct in the database, and between calling them from the database and echoing them nothing happens to it ....

    EDIT: Its getting weirder, sometimes it echos it as 9 and now I noticed it sometimes echos it as 9,95 ...
     
    Dakuipje, Apr 8, 2010 IP
  5. Sabbir

    Sabbir Banned

    Messages:
    210
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    58
    #5
    why don't you try round($price*$ordered);
     
    Sabbir, Apr 8, 2010 IP
  6. Dakuipje

    Dakuipje Peon

    Messages:
    931
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I did, but it outputs exactly the same because $price turns out to be 9 instead of 9,95 ...
    Thats the weird thing, I get the info from a database and in there it is 9,95 but as soon as I put it in a string it becomes 9 ....
     
    Dakuipje, Apr 8, 2010 IP