There are many methods to retain two decimal places in php, such as sprintf, substr, number_format, and round. I will introduce them to you. There are many methods to retain two decimal places in php, such as sprintf, substr, number_format, and round. I will introduce them to you.
Script ec (2); script
Method 1
Sprintf () function. sprintf () function writes formatted strings to a variable.
The Code is as follows: |
|
$ Num = 123213.666666; Echo sprintf ("%. 2f", $ num ); |
Example 2
The Code is as follows: |
|
$ Number = 123; $ Txt = sprintf ("% f", $ number ); Echo $ txt; ?> Output: 123.000000 |
Method 2 substr () function
The Code is as follows: |
|
$ Num = 123213.666666; Echo sprintf ("%. 2f", substr (sprintf ("%. 3f", $ num), 0,-2 )); |
Method 3 number_format () function
The Code is as follows: |
|
$ Number = 1234.5678; $ Nombre_format_francais = number_format ($ number, 2, ','); // 1234,57 $ English_format_number = number_format ($ number, 2, '.', ''); // 1234.57 (I usually use this)
|
Method 4
The round () function rounds a floating point number.
Example
The Code is as follows: |
|
Echo (roround (0.60 )); Echo (roround (0.50 )); Echo (roround (0.49 )); Echo (round (-4.40 )); Echo (round (-4.60 )); ?> Output: 1 1 0 -4 -5 |
If you want to retain decimals, You can retain the decimal places at the root of the parameter.
The Code is as follows: |
|
$ Number = 1234.5678; Echo round ($ number, 2); // 1234.57 |