PHP retains the rounding method of two decimal places-PHP source code

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.