开发者

sprintf (or other function) for contitional formatting of integer / float

I need to display a number registered in database as a float

If the number ha no decimal part, is should be displayed as an int, and as a decimal in other cases.

Example :

8.00 should be displayed 8
8.45 should be displayed 8.45

The existing code uses a wei开发者_如何学Crd (but functionnal solution) using roud() :

if(round($number) == $number) {
 $number = round($number);
}

I wish to find some solution with sprintf by example, to have a more self-explicating code (the actual solution with round is not very understandable)

Does any of you faced this problem and knows a solution (I've tried to play with sprintf() but I dit not managed how to have a variable number of decimals)


Try this:

$numbers = array(
    8.00, 8.45, 20.00, '8.00', '8.45', '20.00'
);

foreach ($numbers as $nr) {
    echo (string)(double)$nr, '<br />';
}


echo +'8.45';

will display 8.45 and

echo +'8.00';

will display 8 ;)


Not quite sure this is what you're looking for, but to shorten your rounding code into one statement, use this.

$number = (int)$number == $number ? (int)$number : $number;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜