views:

48

answers:

2

i have a value that i calculate between 0 -100 , its usually a float number like 5.87876 , so i use number_format like :

$format_number = number_format($number, 2, '.', '');

the problem is , even the calculate number is integer like : 100

its show 100.00

but i want to display it like : 100

what is the elegant way to achive this ?

(i mean without else if ..)

+3  A: 

This is the shortest way I know.

$digits =        (is_numeric($number) && intval($number) == $number ? 0 : 2);
$format_number = number_format($number, $digits, '.', '');

The is_numeric and intval trick is taken from this SO question

Pekka
You copied the trick wrong — I’ve edited to fix it.
Timwi
@Timwi cheers! ` `
Pekka
[NP ☺](http://meta.stackoverflow.com/questions/700/)
Timwi
+2  A: 

so you are trying to have an accuracy of two decimal places after the dot, but suppress the .00 on integers? I'd use sprintf:

$numbers = Array(3.141, 5.87876, 10.9999, 100);


foreach( $numbers as $n ) {
    $string = sprintf("%6.2f\n", $n);
    $string = str_replace(".00", "   ", $string);
    echo $string;
}

The output is

  3.14
  5.88
 11   
100   
bjelli