What is the default precision in PHP?

In PHP, the round() function rounds the floating-point numbers. This tutorial demonstrates how to use PHP’s round() function.

Round the Floating-Point Numbers in PHP

The round() function rounds a floating-point number in PHP. We can use it to define a specific precision value that will round the numbers, keeping the precision value in view.

This precision value can be zero or negative. The function has three parameters; the syntax for this function is:

float round(number, precision, mode);

Where:

  1. The number is the floating-point number we want to round.

  2. The precision is an optional parameter that decides the number of decimal digits to round to. The default precision value is zero.

  3. The mode is an optional parameter to specify a constant, specifying the rounding mode. There are four types of constants for mode:

    Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:

    $a = 1.234;
    $b = 1.2e3;
    $c = 7E-10;
    ?>

    Formally:

    LNUM          [0-9]+
    DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
    EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
    

    The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

    Warning

    Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

    Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

    So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

    Comparing floats

    As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations.

    To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

    $a and $b are equal to 5 digits of precision.

    $a = 1.23456789;
    $b = 1.23456780;
    $epsilon = 0.00001;

    if(abs($a-$b) < $epsilon) {
        echo "true";
    }
    ?>

    NaN

    Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.

    Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan().

    PHP floats can intensively optimize your blocks of code and it is useful to know about their usage. This article will cover floats in detail including their types and syntax used in PHP. We will also take a look at their formatting and how strings can be converted to float numbers. A learning journey full of knowledge about floats awaits you in this article.

    Contents

    PHP Float

    What is the default precision in PHP?
    Float is an important data type that can be used to set fractional values with decimal points. It includes numbers that can be extended to their exponential form. These numbers are also called floating point numbers.

    PHP has an interesting feature of automatically converting the data type of those values to float which are quite large and contain decimal points.

    With a maximum precision of fourteen digits, float numbers tend to lose their precision if they are above this maximum range for digit values. Therefore, you can use the PHP float precision to store values depending on the limit of associated platforms. You can check if variables in PHP are float by using the is_float() and is_double() functions.

    Syntax of Float in PHP

    We advise you to use float as a keyword just before the variable. This is important as it will set float as the data type as that variable is being initialized. In this way, the float value can be set to its initialized variable. You just have to mention it after the name of that variable and an equal sign.

    You can change the float value on any instance in PHP except for one case. The float value cannot be changed if its variable has been declared static. There are certain predefined constants that must be kept in mind while using float as a data type.

    – PHP_FLOAT_MAX

    PHP_FLOAT_MAX is an important predefined constant that represents the largest floating point number presented in a PHP script. PHP_FLOAT_MIN represents the smallest float number that can be presented. Furthermore, – PHP_FLOAT_MAX is also a predefined constant that is used for the smallest negative floating number. You must ensure that you mention its subtraction sign as it is the only different factor in – PHP_FLOAT_MAX compared to PHP_FLOAT_MAX.

    – PHP_FLOAT_DIG

    Moreover, PHP_FLOAT_DIG can be used for numbers with decimal digits that are intended to be rounded into a float. It can also be used to round that float back to those decimal digits without the risk of loss in precision. The PHP floating point can use PHP_FLOAT_EPSILON as a predefined constant for the smallest positive number represented with a variable.

    You can use float as a data type in numerous applications. PHP enables you to use float numbers as marks, currency, and even percentages where decimal points are prevalent. Basic operations like multiplication, addition, division, and subtraction can also be performed on float numbers in PHP. The output values, stored for these operations, depending on the system.

    Types of Floating Point Numbers

    There are three types of floating point numbers in PHP:

    1. Short floating point numbers
    2. Long floating point numbers
    3. Double floating point numbers

    The smallest fixed precision that can be provided through implementation in PHP is called a short floating point number. The minimum exponent size and precision, of this point number, will be five bits and thirteen bits respectively. While it will provide a precision of up to four decimal places.

    One of the largest fixed precisions that can be provided through implementation is called the long floating point number. The minimum exponent size and precision will be eight bits and fifty bits respectively. The precision of this point number will be up to fourteen decimal places.

    One of the fixed precisions that can be provided through implementation is called double floating point number. The minimum exponent size and precision will be the same as that of a long floating point number. It will also provide a precision of up to fourteen decimal places.

    How to Format a Float?

    A float can be formatted by the number_format() function with grouped thousands. However, it is important to note that this function will not support those program executions that have three parameters. The parameters assigned to the values, for this function, are comprised of number, decimals, decimal point, and separator.

    – Do you Need the Number?

    The number is a mandatory parameter, for values, which is comprised of those numbers that have to be formatted. PHP will format the numbers with a comma and without decimal points as the thousands separator if no other parameters have been set. The PHP format float also includes a parameter named decimal which specifies the included decimals. It is an optional parameter that, if set, will format the numbers with dots as their decimal points.

    What About the Decimal Point?

    Moving on, a decimal point is also an optional parameter that specifies the strings that have to be used for decimal points. Whereas, a separator can be used to specify the strings that can be used for the thousands separator. It is up to you to use this parameter as it is optional because only the first character of the separator will be used. However, you must keep in mind that the use of all parameters will become mandatory if the separator is used.

    The return values for the number_format() function will return all the numbers that have been formatted. The changelog for this function will support multiple bytes from the decimal point and separator parameters. Older versions of PHP only used the first byte of all separators.

    How To Convert Strings To Float Numbers?

    PHP enables you to effortlessly convert strings to float numbers based on your preferences. However, there will be not much need to do that as PHP allows implicit type conversions. Still, there are four prevalent methods with which you can convert strings to float numbers.

    – First Method of Conversion

    The first method involves the number_format() function that can also be used to convert strings into float numbers. The formatted numbers are returned if the blocks of code are executed successfully. In another case, a warning named E_WARNING is given upon failure of the execution.

    – Second Method: Typecasting

    PHP convert string to float can be done by a second method called typecasting. With this method, strings can be directly converted to float numbers and doubles. It can also convert them to the primitive type of integers. We advise you to use typecasting in most cases as it is easier and does not require the usage of any function.

    – Third Method: Mathematical Operations

    You can also convert strings to float numbers by performing mathematical operations and adding zero with the values. In this way, the strings will be implicitly converted to their respective float numbers. The PHP string to float conversion also involves the usage of the floatval() function. This function is often used for the conversion of strings into their respective float numbers.

    Floatval() And Intval() Functions

    Floatval() is an inbuilt function in PHP that can be used to return the float values of variables for your blocks of code. In this way, the strings will be converted to their corresponding float numbers. It is important to compare the floatval() function with intval() as they have a similar purpose for usage. The intval() function is used to convert strings into their corresponding integer values.

    It is an inbuilt function within PHP with which you can return the integer values of variables for your blocks of code. The function accepts an optional and a mandatory parameter to convert the associated strings to their respective integers. These parameters include a variable named $var which is the mandatory one.

    This is because it serves in the script to be converted to the respective integer value. In addition, $base is the optional parameter with which the base to convert $var to its integer value is specified. The intval() function will return the corresponding integers of $var as the value. You also have to take the case into account in which the $base has not been specified.

    Conclusion

    Let’s have a quick revision of what has been covered so far. We learned about float as a data type to set fractional values with decimal points and extend numbers to their exponential form. We looked at the syntax that included float as a keyword to set it as the data type and initialize the variable. We saw that the syntax involves certain predefined constants as well. Here are the specifics:

    • What is the default precision in PHP?
      There was also a mention of three types of floating-point numbers named short, long and double.
    • We learned how to format a float using the number_format() function with grouped thousands.
    • Certain parameters named number, decimals, decimal point, and separator are assigned to the values for this function.
    • We also looked at four methods to convert strings into float numbers.
    • These methods involved the usage of the number_format() function, floatval() function, typecasting, performing basic mathematical operations, and adding zero with the numbers.
    • Finally, we compared the floatval() and intval() functions and saw how they convert strings into float numbers and integers respectively.

    If you are unsure about how to use float in PHP, this guide is all that you need. You can come back to it whenever you need to. Happy Coding!

    5/5 - (10 votes)

    What is the default precision in PHP?

    Position is Everything

    Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

    What is precision in PHP?

    Floating point precision. Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16.

    What is the maximum precision in PHP?

    PHP Floats The float data type can commonly store a value up to 1.7976931348623E+308 (platform dependent), and have a maximum precision of 14 digits.

    How to get only 2 digits after decimal in PHP?

    $twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.

    How to remove .00 in PHP?

    $num + 0 does the trick.