$num + 0 does the trick.
SHIFT STRING LEFT DELETING LEADING SPACE (or use 0 to detete 0). SHIFT STRING RIGHT DELETING TRAILING STR or 0.
The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.
$num + 0
does the trick.
echo 125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7
Internally, this is equivalent to casting to float with (float)$num
or floatval($num)
but I find it simpler.
you could just use the floatval
function
echo floatval('125.00');
// 125
echo floatval('966.70');
// 966.7
echo floatval('844.011');
// 844.011
This is what I use:
function TrimTrailingZeroes($nbr) {
return strpos($nbr,'.')!==false ? rtrim(rtrim($nbr,'0'),'.') : $nbr;
}
N.B. This assumes .
is the decimal separator. It has the advantage that it will work on arbitrarily large (or small) numbers since there is no float cast. It also won't turn numbers into scientific notation (e.g. 1.0E-17).
Simply adding +
to your string variable will cause typecast to (float) and removes zeros:
var_dump(+'125.00'); // double(125)
var_dump(+'966.70'); // double(966.7)
var_dump(+'844.011'); // double(844.011)
var_dump(+'844.011asdf');// double(844.011)
For everyone coming to this site having the same problem with commata instead, change:
$num = number_format($value, 1, ',', '');
to:
$num = str_replace(',0', '', number_format($value, 1, ',', '')); // e.g. 100,0 becomes 100
If there are two zeros to be removed, then change to:
$num = str_replace(',00', '', number_format($value, 2, ',', '')); // e.g. 100,00 becomes 100
More here: PHP number: decimal point visible only if needed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With