Home >Backend Development >PHP Tutorial >How to Efficiently Remove Leading and Trailing Zeros from Decimal Numbers in PHP?

How to Efficiently Remove Leading and Trailing Zeros from Decimal Numbers in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 00:30:30847browse

How to Efficiently Remove Leading and Trailing Zeros from Decimal Numbers in PHP?

Eliminating Redundant Zeros from Decimal Numbers in PHP

Question:

How can I efficiently remove trailing and leading zeroes from decimal numbers in PHP? I need a method that handles values such as:

  • 125.00 -> 125
  • 966.70 -> 966.7
  • 844.011 -> 844.011

Answer:

PHP offers a simple solution using the ' ' operator:

<code class="php">echo 125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7</code>

Explanation:

Internally, this operation coerces the number to a float using either (float)$num or floatval($num). However, this approach is less cryptic and provides an optimized way to remove useless zero digits from decimals in PHP.

The above is the detailed content of How to Efficiently Remove Leading and Trailing Zeros from Decimal Numbers in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn