Reputation: 7901
I have numbers that look like this:
175.0000
185.0000
195.0000
205.0000
13.0000
15.0000
But I also have numbers that look like this:
10.5000
7.5000
The function number_format()
is not cutting it because, if I set it to leave 1
decimal place, it will leave the .0
in the numbers that aren't 7.5
or 10.5
.
Is there a function that will only display a decimal point if it is greater than 0
?
Upvotes: 0
Views: 1827
Reputation: 60
try this:
$arr=[175.0000, 185.0000, 195.0000, 205.0000, 13.0000, 15.0000, 10.5000, 7.5000 ];
foreach ($arr as $value) {
echo round($value,2)."\n";
}
This will work for sure!
Upvotes: 1
Reputation: 11
Try this
$a = Array("13.0000",
"15.0000",
"10.5000",
"7.5000");
$a = preg_replace('/0+$/', "", $a);
$a = preg_replace('/[.]$/', "", $a);
Result = 13, 15, 10.5, 7.5
Upvotes: 1
Reputation: 19764
You can compare the number with its integer value to check the number of decimal you need:
$num = 7.0;
echo number_format($num, ($num == (int)$num) ? 0 : 1);
$num = 7.5;
echo number_format($num, ($num == (int)$num) ? 0 : 1);
Output:
7
7.5
A shorter version only if you need 1 decimal:
echo number_format($num, $num != (int)$num); // bool to int = 0 or 1.
Another way is to use rtrim()
twice: first for zéros, second for dot:
echo rtrim(rtrim(number_format($num, 3), '0'),'.');
Upvotes: 1
Reputation: 505
I'm not very experienced with php but I found this
echo 13.00 + 0; //gives you 13
echo '125.00' + 0; //gives you 125
echo 76.5 + 0; //gives you 76.5
Upvotes: 1
Reputation: 4814
This isn't in PHP, but is the general algorithm.
There are several ways to do this:
if unformattedNumber % 1 == unformattedNumber:
formattedNumber = number_format(unformattedNumber)
else:
formattedNumber = number_format(unformattedNumber, 1)
or
formattedNumber = number_format(unformattedNumber, 1)
if formattedNumber[-1] == 0:
formattedNumber = number_format(formattedNumber)
Upvotes: 0