Skip to content

Instantly share code, notes, and snippets.

@cdnsteve
Created January 15, 2014 14:47
Show Gist options
  • Save cdnsteve/8437543 to your computer and use it in GitHub Desktop.
Save cdnsteve/8437543 to your computer and use it in GitHub Desktop.
PHP Number converter - converts any number format (English, French, Strings, ints) and returns double (float)
<?php
function validateCleanPrice($num) {
$cleanString = preg_replace('/([^0-9\.,])/i', '', $num);
$onlyNumbersString = preg_replace('/([^0-9])/i', '', $num);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
$removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
return (float) str_replace(',', '.', $removedThousendSeparator);
}
$en_num = "$18 000.08";
$fr_num = "180,000,08 $";
$float_num = 18.08;
$str_num = "18.08";
$int_num = 18;
$boban_num = "18 000,00 $";
$boban_num2 = "18 000,54 $";
$en_clean = validateCleanPrice($en_num);
var_dump($en_clean );
print("\n");
$fr_clean = validateCleanPrice($fr_num);
var_dump($fr_clean);
print("\n");
$float_clean = validateCleanPrice($float_num);
var_dump($float_clean);
print("\n");
$str_clean = validateCleanPrice($str_num);
var_dump($str_clean);
print("\n");
$int_clean = validateCleanPrice($int_num);
var_dump($int_clean);
print("\n");
$boban_clean = validateCleanPrice($boban_num);
var_dump($boban_clean);
print("\n");
$boban_clean2 = validateCleanPrice($boban_num2);
var_dump($boban_clean2);
print("\n");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment