Skip to content

Instantly share code, notes, and snippets.

@mikehins
Last active January 6, 2020 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehins/47c20ca41191d21885c2a3b33b236446 to your computer and use it in GitHub Desktop.
Save mikehins/47c20ca41191d21885c2a3b33b236446 to your computer and use it in GitHub Desktop.
Real filter float helper
<?php
$data = array(
0 => '1,000.214525844156$', // 1000.21
1 => '1,250.2525698', // 1250.25
2 => '10', // 10.00
3 => 100.21236985, // 100.21
4 => '1,10', // 1.10
5 => '1,000,000,01' // 1000000.01
);
function filter_float($value, $decimal = 2)
{
$value = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
if (preg_match('/[,|\.](\d*)$/', $value, $match)) {
$value = preg_replace('/' . $match[0] . '$/', '.' . $match[1], $value);
}
return bcadd(0, floor(str_replace(',', '', $value) * 100) / 100, $decimal);
}
foreach($data as $amount){
echo filter_float($amount) . '<br />';
}
?>
<pre>
0 => '1,000.214525844156$', // 1000.21
1 => '1,250.2525698', // 1250.25
2 => '10', // 10.00
3 => 100.21236985, // 100.21
4 => '1,10', // 1.10
5 => '1,000,000,01' // 1000000.01
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment