Floating-point cheat sheet for PHP

Floating-Point Types

PHP is dynamically typed and will often convert implicitly between strings and floating-point numbers (which are platform-dependant, but typically IEEE 64 bit values). To force a value to floating-point, cast it:

	$foo = (float)'10.5'; 

Decimal Types

The BC Math and Decimal extensions implement arbitrary-precision decimal math:

	$a = '0.1';
	$b = '0.2';
	echo bcadd($a, $b);     // prints 0.3

	$a = new Decimal('0.1');
	$b = new Decimal('0.2');
	echo $a + $b;           // prints 0.3 

How to Round

Rounding can be done with the number_format() function:

	$number = 4.123;
	echo number_format($number, 2); // prints 4.12

If you are using the decimal extension, you can round using the round method:

	$decimal = new Decimal("4.123");
            echo $decimal->round(2);        // prints 4.12            


© Published at floating-point-gui.de under the Creative Commons Attribution License (BY)

Fork me on GitHub