how do i do this

Discussion in 'PHP' started by pizzaman, Nov 9, 2007.

  1. #1
    i have some math calculation and i want to format the result so it is something like
    02.00 rather than 2
    12.20 rather than 12.2
     
    pizzaman, Nov 9, 2007 IP
  2. mvl

    mvl Peon

    Messages:
    147
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You could use a combination of number_format() and str_pad(). The rsult will be a string:

    
    // assuming the result is in $result
    ...
    $formatted = str_pad(number_format($result, 2, '.', ''), 5, '0', STR_PAD_LEFT);
    ...
    // now $formatted is a string containing the formatted result
    
    
    Code (markup):
    explanation: number_format() formats $result to have two decimals, a '.' as the decimal separator. The last parameter is required and indicates we will not use a thousands-separator.
    str_pad() pads the resulting formatted string so it will contain five characters, use the '0' for padding, and pad on the left.
     
    mvl, Nov 9, 2007 IP
  3. bartolay13

    bartolay13 Active Member

    Messages:
    735
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    98
    #3
    try this one hope this helps

    $a = 2;
    $new = sprintf("%02s", $a);
    echo $new;

    might give you an idea for the string..
     
    bartolay13, Nov 9, 2007 IP