Reputation: 9530
What is the best solution to convert a number to:
Example:
if ($num == 8.2) //display 8.2
if ($num == 8.0) //display 8
Note: I won't have numbers like 8.22 or 8.02. I will have this type of numbers:
1, 1.2, 1.4 ... 2.6, 2.8, 3 ....9.8, 10
Upvotes: 0
Views: 2905
Reputation: 41810
If you know for sure that all of your numbers will be in that format, you should be able to just use round
. (Normally, round
does not work well for formatting, but in this case it should do the job.)
foreach ([8, 8.2, 1, 1.2, 1.4, 2.6, 2.8, 3, 9.8, 10] as $number) {
echo round($number, 1) . PHP_EOL;
}
Some might assume otherwise, but echo round(8.0, 1);
displays 8
, not 8.0
.
Upvotes: 5
Reputation: 2847
Using floor and some arithmetic and number_format
$num = 8.0;
//8.0 - 8 = 0
//8.2 - 8 = .2
if($num - floor($num)>0) {
// Leaves 1 decimal
echo number_format($num,1);
// or if rounding
//echo round($num, 1);
} else {
// Leaves 0 decimal
echo number_format($num,0);
// or if rounding
//echo round($num, 0);
}
Upvotes: 0
Reputation: 4021
if (abs($num - (int)$num) < 0.001)
echo (int)$num;
else
echo number_format($num, 1);
Upvotes: 1