Home>Article>Backend Development> How to convert php to 2 digits

How to convert php to 2 digits

藏色散人
藏色散人 Original
2022-11-29 09:57:29 1145browse

How to convert php into a 2-digit number: 1. Create a php sample file; 2. Define the "function reverse_format($num,$precision=2){...}" method; 3. Pass " round($num,$precision);" only needs to retain 2 decimal places.

How to convert php to 2 digits

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.

How to convert php to 2 digits?

Formatting numbers in PHP, retaining 2 digits or specified digits

The code is as follows:

/** * 数字格式化 * @param $num 要格式划的数字 * @param $precision 保留小数点位数 */ function reverse_format($num,$precision=2) { $_num = round($num,$precision); //保留$precision位小数 if($precision==0) return $_num; $arr = explode('.',$_num); //拆分数字 $cnt = count($arr); if($cnt==1) { $len = 0; }else{ $len = strlen($arr[1]); } //由后补0组成的字符串 $_str = ''; for($i=0;$i<$precision-$len;$i++) { $_str .= '0'; } if($cnt==1) { $_str1 = ''; }else{ $_str1 = $arr[1]; } //拼接为最后的字符串 $result = $arr[0].".".$_str1.$_str; return $result; }

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How to convert php to 2 digits. 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