PHP float

Created with Sketch.

PHP float

Summary: in this tutorial, you’ll learn about floating-point numbers or floats in PHP.

Introduction to the PHP float

Floating-point numbers represent numeric values with decimal digits.

Floating-point numbers are often referred to as floats, doubles, or real numbers. Like integers, the range of the floats depends on the platform where PHP runs.

PHP recognizes floating-point numbers in the following common formats:

1.25
3.14
-0.1

Code language: CSS (css)

PHP also supports the floating-point numbers in scientific notation:

0.125E1 // 0.125 * 10^1 or 1.25

Code language: JSON / JSON with Comments (json)

Since PHP 7.4, you can use the underscores in floats to make long numbers more readable. For example:

1_234_457.89

Code language: CSS (css)

Floating-point number accuracy

Since the computer cannot represent exact floating-point numbers, it only can use approximate representations.

For example, the result of 0.1 + 0.1 + 0.1 is 0.299999999…, not 0.3. It means that you must be careful when comparing two floating-point numbers using the == operator.

The following example returns false, which may not what you expected:

<?php

$total = 0.1 + 0.1 + 0.1;
echo $total == 0.3; // return false

Code language: HTML, XML (xml)

Test a float value

To check if a value is a floating-point number, you use the is_float() or is_real() function. The is_float() returns true if its argument is a floating-point number; otherwise, it returns false. For example:

echo is_float(0.5);

Code language: CSS (css)

Output:

1

 

Summary

  • Floating-point numbers are numbers with decimal points. Floating-point numbers are also known as floats.
  • PHP can only represent floats approximately, not precisely.

Leave a Reply

Your email address will not be published. Required fields are marked *