Home >Backend Development >PHP Problem >How to remove extra 0 after decimal point in php

How to remove extra 0 after decimal point in php

青灯夜游
青灯夜游Original
2021-09-07 18:23:215150browse

Method: 1. Use "decimal 0"; 2. Use "floatval(decimal)"; 3. Use "rtrim(rtrim(decimal,'0'),'.')"; 4. Use "preg_replace('/[.]$/','',preg_replace('/0 $/','', decimal)".

How to remove extra 0 after decimal point in php

This Tutorial operating environment: Windows 7 system, PHP 7.1 version, DELL G3 computer

Today we introduce several methods to remove the 0 at the end of the decimal point:

Method 1. Add directly 0

##Because PHP is a weak type, it can directly perform mathematical operations and convert them into numbers.

<?php
echo &#39;100.00&#39; + 0 ."<br>";
echo &#39;100.01000&#39; + 0 ."<br>";
echo &#39;100.10000&#39; + 0 ."<br>";
?>

Output result:


100
100.01
100.1

Method 2, use floatval() to convert to floating point

<?php
echo floatval(&#39;100.00&#39;)."<br>";
echo floatval(&#39;100.01000&#39;)."<br>";
echo floatval(&#39;100.10000&#39;)."<br>";
?>

Output result:

100
100.01
100.1

Method 3, use rtrim ()Function

<?php
echo rtrim(rtrim(&#39;100.00&#39;, &#39;0&#39;), &#39;.&#39;)."<br>";
echo rtrim(rtrim(&#39;100.01000&#39;, &#39;0&#39;), &#39;.&#39;)."<br>";
echo rtrim(rtrim(&#39;100.10000&#39;, &#39;0&#39;), &#39;.&#39;)."<br>";
?>

Output result:

100
100.01
100.1

Method 4. Use regular expression

正则表达式说明:
/0+$/  去掉末尾多余的0
/[.]$/ 去掉末尾的.

943305d0cdc8533a04f5034bb4fe0156";
echo preg_replace('/[.]$/', '', preg_replace('/0+$/', '', '100.1000'))."0c6dc11e160d3b678d68754cc175188a";
echo preg_replace('/[.]$/', '', preg_replace('/0+$/', '', '100.010203000'))."0c6dc11e160d3b678d68754cc175188a";
?>
Output results:

100
100.1
100.010203

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to remove extra 0 after decimal point 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