Home > Backend Development > PHP Tutorial > How to format numbers in php and add 0 in front of insufficient digits

How to format numbers in php and add 0 in front of insufficient digits

WBOY
Release: 2016-07-25 09:00:30
Original
1627 people have browsed it
PHP formats numbers. When there are insufficient digits, add 0 in front to make up for it. This article provides two implementation methods, using sprintf and number_format respectively. Friends in need, come and take a look.

Example of php formatting numbers.

<?php   
 $var=sprintf("%04d", 2);//生成4位数,不足前面补0   
 echo $var;//结果为0002   
?>
Copy after login

1. String sprintf() function Grammar

sprintf(format,arg1,arg2,arg++)

Parameters Description
format Required. Convert format.
arg1 Required. Specifies the parameters to be inserted at the first % sign in the format string.
arg2 Optional. Specifies the parameter to be inserted into the format string at the second % sign.
arg++ Optional. Specifies the parameters to be inserted into the format string at the third, fourth, etc. % symbols.
illustrate

The parameter format is the format of the conversion, starting with the percent sign ("%") and ending with the conversion character. The following possible format values ​​are: %% - returns the percent symbol %b - binary number %c - character according to ASCII value %d - signed decimal number %e - Continuous counting method (e.g. 1.5e+3) %u - unsigned decimal number %f - floating point number (local settings aware) %F - floating point number (not local settings aware) %o - octal number %s - string %x - hexadecimal number (lowercase letters) %X - Hexadecimal number (capital letters)

arg1, arg2, ++, etc. are inserted into the main string at the percent sign (%) symbol. This function is executed step by step. At the first % sign, arg1 is inserted, at the second % sign, arg2, and so on. Example:

<?php   
 $number = 123;   
 $txt = sprintf("%f",$number);   
 echo $txt;   
?> 
Copy after login

2. Format number function number_format() Example:

<?php
//number_format 格式化数字
$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

//by http://bbs.it-home.org
?>
Copy after login


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