Remove useless zero digits from decimals in PHP
✔ Recommended Answer
$num + 0
does the trick.
echo 125.00 + 0; // 125echo '125.00' + 0; // 125echo 966.70 + 0; // 966.7
Internally, this is equivalent to casting to float with (float)$num
or floatval($num)
but I find it simpler.
Source: stackoverflow.com
Answered By: lafor
To remove useless zero digits from decimals in PHP, you can use the rtrim()
and number_format()
functions together. Here's an example:
php$number = 12.3400;
// Use number_format() to format the number with 2 decimal places
$formatted = number_format($number, 2);
// Use rtrim() to remove any trailing zeros
$formatted = rtrim($formatted, '0');
// If the last character is a decimal point, remove it as well
$formatted = rtrim($formatted, '.');
echo $formatted; // Outputs "12.34"
In this example, the number_format()
function is used to format the number with 2 decimal places. The resulting string includes trailing zeros, so the rtrim()
function is used to remove them. If the last character in the resulting string is a decimal point, it is also removed.
Note that this approach assumes that you always want to display the number with 2 decimal places. If you want to display a variable number of decimal places, you can use the round()
function with a precision argument to round the number to the desired number of decimal places before formatting it with number_format()
.
Comments
Post a Comment