"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-12-15
Browse:974

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:

echo 125.00   0; // 125
echo '125.00'   0; // 125
echo 966.70   0; // 966.7

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3