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

How to remove the trailing 0 from decimals in php

青灯夜游
青灯夜游Original
2021-06-02 19:18:202668browse

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

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

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

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

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

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!

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