kemar
kemar

Reputation: 91

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 weird (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)

Upvotes: 0

Views: 286

Answers (3)

Yoshi
Yoshi

Reputation: 54649

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 />';
}

Upvotes: 1

nikc.org
nikc.org

Reputation: 16972

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;

Upvotes: 0

MatTheCat
MatTheCat

Reputation: 18721

echo +'8.45';

will display 8.45 and

echo +'8.00';

will display 8 ;)

Upvotes: 0

Related Questions