Reputation: 125456
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 ..)
Upvotes: 2
Views: 653
Reputation: 10070
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
Upvotes: 2
Reputation: 449385
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
Upvotes: 4