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

青灯夜游
Release: 2023-03-12 11:36:02
Original
5122 people have browsed it

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>";
?>
Copy after login

Output result:


100
100.01
100.1
Copy after login
Copy after login
Copy after login

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>";
?>
Copy after login

Output result:

100
100.01
100.1
Copy after login
Copy after login
Copy after login

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>";
?>
Copy after login

Output result:

100
100.01
100.1
Copy after login
Copy after login
Copy after login

Method 4. Use regular expression

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

<?php
echo preg_replace(&#39;/[.]$/&#39;, &#39;&#39;, preg_replace(&#39;/0+$/&#39;, &#39;&#39;, &#39;100.00&#39;))."<br>";
echo preg_replace(&#39;/[.]$/&#39;, &#39;&#39;, preg_replace(&#39;/0+$/&#39;, &#39;&#39;, &#39;100.1000&#39;))."<br>";
echo preg_replace(&#39;/[.]$/&#39;, &#39;&#39;, preg_replace(&#39;/0+$/&#39;, &#39;&#39;, &#39;100.010203000&#39;))."<br>";
?>
Copy after login

Output results:

100
100.1
100.010203
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template