views:

332

answers:

6

Hi all,

I want to use number_format function in PHP. For example:

$number = 234.51;
echo number_format($number,2);

This works for float numbers but I want to use it for different numbers. If a number is decimal and doesn't have any floating points, it shows like : 145.00 . How can I fix this? I mean I want to show as many floating points as needed, not more.

Thanks in advance

+3  A: 

Investigate the printf and sprintf functions instead of number_format.

They give the ability to format numbers as you wish.

printf("%d", $int)

would be appropriate for a decimal integer.

printf("%4.2f", $float)

would be appropriate for a floating point number with two decimal places.

number_format seems to be intended for internationalisation of currency output, but I don't think that's what you want because you mentioned decimal 'whole' numbers.

pavium
+1  A: 

I don't know a better way to do this, but you can compare the type, like the code below:

$number = 234.159;
if(is_float($number)) {
 echo number_format($number, 2);
}else {
 echo $number;
}
Lucas Renan
+1  A: 

Whilst it's a bit quick and dirty, you could simply do a...

str_replace('.00', '', number_format($potentialFloat, 2));

Far from ideal, but effective.

middaparka
+2  A: 

I think I can't get what I want from number_format so I did this and it works fine :

 public function floatNumber($number)
 {
      $number_array = explode('.',$number);
      $left = $number_array[0];
      $right = $number_array[1];
      return number_format($number,strlen($right));
 }

thanx all for your replies.

Ali Bozorgkhan
+1  A: 

I think the key problem is defining how many positions are needed. Would you define 13.01 as 13 because the first decimal was a 0? Since printf and number format needs you to know how many decimals, I don't know that that would work for you.

Maybe something like this (which is a lot of functions, but looks for the first 0, and then returns the truncated string). Yes, it is intensive, but it may be the best way for you.

function show_number($number, $max = 8){
  if(strpos($number, '.')){
    $decimal = strpos($number, '.');
    if(strpos($number, '.0')){
      return substr($number, 0, $decimal);//returns whole if zero is first
    } else {
      if(strpos(substr($number, $decimal, $max), '0')){
        $zero = strpos(substr($number, $decimal, $max), '0');
        return substr($number, 0, $decimal+$zero);//returns number w/0 first zero
      } else {
        return substr($number, 0, $decimal+$max+1); //returns number with max places
      }
    }
  } else {
    return $number; //returns number if no decimals
  }
}
Cryophallion
A: 
rtrim(number_format($number, 2), '0.');
sanmai