Number_format issue in rounding decimal places

Discussion in 'PHP' started by san321, Sep 30, 2007.

  1. #1
    Hi Guys,
    The original code below would output a number with 2 or four decimal places.
    (str_replace(',', '', $row['price']) * 1.1 ) . "\n";
    Code (markup):
    What I need to do is round it up/down to 2 decimal places.
    I tried the below code and it was a disaster, it displays a number that was 3438.545 as 3.30

    number_format(str_replace(',$', '', $row['price']) * 1.1, 2, '.', '' ) . "\n";
    Code (markup):
    Any ideas on where I am going wrong? What I want it to show is 3438.55
    The "*1.1" is a tax calculation, I also had to strip a , and a $ from the numbers.
     
    san321, Sep 30, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Perhaps:
    
    round(intval($row['price']) * 1.1, 2);
    
    PHP:
    ??


    If not, can you show me an example of what $row['price'] holds?
     
    nico_swd, Sep 30, 2007 IP
  3. kendo1979

    kendo1979 Peon

    Messages:
    208
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] )

    number format is used to show number grouped in thousands.
    if you want to show a number as a variable, you might wanna look at sprintf which formats your given number to any type you like. then output the result with number format to show correctly placed dots and commas using your locale.
     
    kendo1979, Oct 2, 2007 IP
  4. codyrockx

    codyrockx Peon

    Messages:
    33
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Sprintf would work well:
    sprintf( '%.2f', ($row['price'] * 1.1) );
    Code (markup):
     
    codyrockx, Oct 2, 2007 IP
  5. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #5
    The problem was in your str_replace, you are trying to replace ",$" together and not separately.

    str_replace(array(',', '$'), '', $row['price'])
    PHP:
     
    krt, Oct 2, 2007 IP