Home > Article > Backend Development > How to Efficiently Remove Trailing Zeros from Decimal Numbers in PHP?
Removing Trailing Zeros from Decimal Numbers in PHP
In PHP, removing trailing zero digits from decimals can be a common task. Consider the following scenario: you have a set of numbers like 125.00, 966.70, and 844.011 that you want to display without the unnecessary zero digits.
Fast and Optimized Solution
To accomplish this efficiently, you can employ the simple yet effective solution of adding the number to 0. This technique, represented by $num 0, casts the number to a float and removes any trailing zeros.
<code class="php">echo 125.00 + 0; // Output: 125 echo '125.00' + 0; // Output: 125 echo 966.70 + 0; // Output: 966.7</code>
Equivalent Castings
Internally, this method is equivalent to casting the number to a float using (float)$num or floatval($num). However, adding to 0 provides a more straightforward and concise approach.
By leveraging this optimized solution, you can quickly remove trailing zero digits from decimals in PHP without compromising efficiency.
The above is the detailed content of How to Efficiently Remove Trailing Zeros from Decimal Numbers in PHP?. For more information, please follow other related articles on the PHP Chinese website!