Home > Backend Development > PHP Problem > How to remove the trailing 0 from decimals in php

How to remove the trailing 0 from decimals in php

青灯夜游
Release: 2023-03-10 10:06:02
Original
2773 people have browsed it

php method to remove the trailing 0 from a decimal: 1. Use the " " operator to add 0 directly, for example "'100.00' 0"; 2. Use the floatval() function to convert to a floating point type; 3. Use rtrim() function; 4. Use the preg_replace() function with the regular expression "/[.]$/".

How to remove the trailing 0 from decimals in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Today I will introduce several ways to remove the 0 at the end of the decimal point Method:

例如:100.00、100.01、100.10
得到值:100、100.01、100.1
Copy after login

Method 1.

Use the " " operator and add 0 directly, because PHP is a weak type and can directly perform mathematical operations and convert it into a number.

echo '100.00' + 0;
echo '100.01' + 0;
echo '100.10' + 0;

// 结果
100
100.01
100.1
Copy after login

Method 2,

Use floatval() to convert to floating point type.

echo floatval('100.00');
echo floatval('100.01');
echo floatval('100.10');

// 结果
100
100.01
100.1
Copy after login

Method 3.

Use the rtrim() function.

echo rtrim(rtrim('100.00', '0'), '.');
echo rtrim(rtrim('100.01', '0'), '.');
echo rtrim(rtrim('100.10', '0'), '.');

// 结果
100
100.01
100.1
Copy after login

Method 4.

Use regular expressions.

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

echo preg_replace('/[.]$/', '', preg_replace('/0+$/', '', '100.00'));
echo preg_replace('/[.]$/', '', preg_replace('/0+$/', '', '100.01'));
echo preg_replace('/[.]$/', '', preg_replace('/0+$/', '', '100.10'));

// 结果
100
100.01
100.1
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove the trailing 0 from decimals 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