Best practice using PHP float

I read the Floating Point Guide on using the float type in PHP. The answer is to use the BC Math extension. Using strings can represent float as an exact type and prevent problems with float and integer.

In the meantime, I did not find any good examples on Github and on this site working with the math BC extension. What is a clean way to get PHP to use strings, how to evaluate them?

Is it especially best to use the BC Math extension with MySQL DECIMAL data types?

My test example is with PHP 5.4.10, the correct answer is: 0.2999999999996

<?php
bcscale(13);

$a = '0.3';
$b = '0.0000000000004';

echo $a-$b; // 0.3
echo '<br />';
echo bcsub($a, $b); // 0.2999999999996
echo '<hr />';

$a = "0.3";
$b = "0.0000000000004";

echo $a-$b; // 0.3
echo '<br />';
echo bcsub($a, $b); // 0.2999999999996
echo '<hr />';

$a = 0.3;
$b = 0.0000000000004;

echo $a-$b; // 0.3
echo '<br />';
echo bcsub($a, $b); // 0.3000000000000
echo '<hr />';

$a = '0.3';
$b = '0.0000000000004' + 0;

echo $a-$b; // 0.3
echo '<br />';
echo bcsub($a, $b); // 0.3000000000000
echo '<hr />';

$a = (string) 0.3;
$b = (string) 0.0000000000004;

echo $a-$b; // 0.3
echo '<br />';
echo bcsub($a, $b); // 0.3000000000000
echo '<hr />';

$a = strval(0.3);
$b = strval(0.0000000000004);

echo $a-$b; // 0.3
echo '<br />';
echo bcsub($a, $b); // 0.3000000000000
?>
+5
source share
1 answer

- BC Math, GMP. . GMP 30 , BC.

DECIMAL (12, 0) DECIMAL (27,0) php start suck apr. 10 ^ 19 . -:

//PHP Version 5.3.10,  FreeBSD 8.2-RELEASE amd64

$a = pow(10, 18);
var_dump($a, $a > ($a - 1), ($a - 1) > $a, ($a - 1) == $a, ($a - 1) === $a);
// int(1000000000000000000)
// bool(true)
// bool(false)
// bool(false)
// bool(false)

$a = pow(10, 19);
var_dump($a, $a > ($a - 1), ($a - 1) > $a, ($a - 1) == $a, ($a - 1) === $a);

// double(1.0E+19)
// bool(false)
// bool(false)
// bool(true)
// bool(true)

Decimal, . , php BC , . Yupp, , , , ?

P.S. PHP Secure Communications - Math_BigInteger, , .

:, PHP 5.6 GMP , gmp ( ).

+4

All Articles