Php format number: Add 0 to complement the front when the number of digits is not enough, php format number: Add 0 to complement the front when the number of digits is not enough
Instance first, and then explain
PHP code
$ Var = sprintf ("% 04d", 2); // generate four digits. If not, add 0.
Echo $ var; // result 0002
?>
PHP string sprintf () function
Syntax
sprintf(format,arg1,arg2,arg++)
Parameters |
Description |
Format |
Required. Conversion format. |
Arg1 |
Required. Specifies the parameter inserted at the first % symbol in the format string. |
Arg2 |
Optional. Specifies the parameter inserted at the second % symbol in the format string. |
Arg ++ |
Optional. Specifies the parameters inserted to the third, fourth, and other % symbols in the format string. |
Description
ParametersFormatIs the conversion format, starting from the percent sign ("%") to the end of the conversion character. PossibleFormatValue:
- %-Percentage sign returned
- % B-binary number
- % C-Characters Based on ASCII values
- % D-Signed decimal number
- % E-resumable counting (for example, 1.5e + 3)
- % U-Unsigned decimal number
- % F-floating point number (local settings aware)
- % F-floating point number (not local settings aware)
- % O-octal values
- % S-string
- % X-hexadecimal (lowercase letter)
- % X-hexadecimal (uppercase letters)
Parameters such as arg1, arg2, ++ are inserted to the percent sign (%) in the main string. This function is executed step by step. In the first % symbol, insert arg1, at the second % symbol, insert arg2, and so on.
PHP code
-
- $ Number = 123;
- $ Txt = sprintf ("% f", $ number );
- Echo $ txt;
- ?>
Format number number_format ()
Instance:
$ 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
?>