<?php
$tests = ['1613938511.464898123456789', '1613938511.464898923456789', '1613938511.123456789', '1613938511.12345678910', '1613938519.123456789', '1613938511.999999', '1613938511.999999999999'];
foreach ($tests as $test)
{
echo "Testing : $test\n";
$f = (float)$test;
// echo " string=" . $f . " | json =" . json_encode($f);
$jsonOne = substr(json_encode($f),0,17);
$testOne = substr($test,0,17);
echo "\n> Test passed :" . $jsonOne ." =?= ". $testOne . " ::: " . ($jsonOne === $testOne ? 'yes' : 'no');
echo "\n-------------------------------------------------\n";
}
// more complex testing
$test1MResults = [];
$testFailed = [];
for ($i = 0; $i < 1000000; $i++) {
$testFloat = '1613938511.' . $i;
$floatN = (float) $testFloat;
$jsonN = json_encode($floatN);
$floatJsonN = (float) $jsonN;
$absN = (int) abs($floatN - $floatJsonN) * 1000000;
/**
* Why using or when compare text faild ? because json delete the zero at end of a float , but in our testFloat its composed string 'xx'.$i (10)
* Why using int comparasion ? to strict verify that $floatN === $floatJsonN with the 6 digits
*
* You can play with conditions to see example of fails (that are not really a fail but just a wrong comparasion method)
*/
$passed = ($jsonN === $testFloat || $absN === 0);
$test1MResults[] = $passed;
if (false === $passed) {
$testFailed[] = [$i, $jsonN, $testFloat, $absN, gettype($absN)];
}
}
$totalTests = count($test1MResults);
$totalSuccess = count(array_filter($test1MResults));
$totalFails = $totalTests - $totalSuccess;
print_r("Total Success : " . $totalSuccess . "\n");
print_r("Total Fails : " . ($totalFails) . "\n");
if ($totalFails > 0) {
$maxShow = 10 > $totalFails ? $totalFails : 10;
for ($i=0; $i < $maxShow; $i++) {
print_r(json_encode($testFailed[$i]));
echo "\n";
}
for ($i=$totalFails; $i > $totalFails - $maxShow; $i--) {
print_r(json_encode($testFailed[$i]));
echo "\n";
}
}
echo "\n\n";
/**
* Total Success : 1000000
* Total Fails : 0
*/
preferences:
44.04 ms | 402 KiB | 5 Q