PHP Number Format – Remove Trailing Zeros
In PHP, you can use the number_format
function to format numbers and remove trailing zeros. The number_format
function is used to format a number with grouped thousands and decimal points.
To remove trailing zeros from a formatted number, you can use the rtrim
function. The rtrim
function is used to remove characters from the right side of a string.
Here is an example of how to remove trailing zeros using PHP:
$number = 123.4500;
$formattedNumber = number_format($number, 2);
$trimmedNumber = rtrim($formattedNumber, '0');
echo $trimmedNumber;
In this example, we start with a number (123.4500) and format it using number_format
with 2 decimal places. The resulting formatted number is “123.45”. We then use rtrim
to remove any trailing zeros, resulting in the final number “123.45”. Finally, we echo the trimmed number.
Here’s another example using a larger number:
$number = 98765.000;
$formattedNumber = number_format($number, 2);
$trimmedNumber = rtrim($formattedNumber, '0');
echo $trimmedNumber;
In this example, the original number is 98765.000. After formatting it with number_format
and trimming the trailing zeros, the final number becomes “98765”.