PHP_ decimal/rounding/upward/lower

Source: Internet
Author: User
Decimal Example:


PHP reserved two decimal places and rounded

$n =0.1265489;echo sprintf ("%.2f", $n); 0.13

As you can see, we used the sprintf function to format the $n%.2f is the target format, where 2 means that two-bit f means float (floating-point) 3rd is a decimal 6 is rounded

Let's look at an example.


$n =0.1265489echo substr (sprintf ("%.3", $n), 0,-1);//0.12

The code outputs a reserved 2 for decimals without rounding, in fact we understand that the sprintf feature will round the decimal number after we reserve a bit, and then use SUBSTR to intercept the first 2 bits



Take the whole example:


Echo ceil (4.1);    5echo ceil (9.999);  10

The Ceil function is to take the whole function upward, what is it called upward? That means if it goes a little bit, go ahead. A 4.1 becomes 5 in the example.


On the contrary, there's a function called floor, and we'll look at its usage.


Echo Floor (4.1);   4echo floor (9.999); 9

The floor's characteristics are particularly evident in the second output, which is that no number of decimals is given to you, even if it is infinitely close to 10, and the integer that is not taken down is 9.


Round function


 
  


The description of the round function in the PHP manual is:

Float round (float $val [, int $precision = 0 [, int $mode = php_round_half_up]])

Returns the result of rounding Val based on the specified precision precision (number of digits after decimal point). Precision can also be negative or 0 (the default value).

Round parameter one is the data source, parameter two is to keep the decimal place and then one (for example, you enter 2 so the 3rd is after a bit) is rounded, when he is negative, from the last point of the data source to start the corresponding length of 0 and the last rounding such as round (123456,- 2) is 123456 from 6 onwards the number of two bits into 0, and the last one 5 (from the back of the first digit is 6 the last is 5) is rounded, output 123500

  • 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.