Skip to content

Instantly share code, notes, and snippets.

@cgmartin
Created June 27, 2012 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cgmartin/3004926 to your computer and use it in GitHub Desktop.
Save cgmartin/3004926 to your computer and use it in GitHub Desktop.
Float and NumberFormatter oddity
Old validators with Zend\Locale\Format, passing:
public function deLocaleStringsProvider()
{
return array(
array('1,3', true),
array('1000,3', true),
array('1.000,3', true),
array('1.3', false),
array('1000.3', false),
array('1,000.3', false),
);
}
public function enLocaleStringsProvider()
{
return array(
array('1.3', true),
array('1000.3', true),
array('1,000.3', true),
array('1,3', false), // !!!
array('1000,3', false), // !!!
array('1.000,3', false), // !!!
);
}
New tests, with NumberFormatter:
public function deLocaleStringsProvider()
{
return array(
array('1,3', true),
array('1000,3', true),
array('1.000,3', true),
array('1.3', true), //???
array('1000.3', true), //???
array('1,000.3', true), //???
);
}
public function enLocaleStringsProvider()
{
return array(
array('1.3', true),
array('1000.3', true),
array('1,000.3', true),
array('1,3', true), //???
array('1000,3', true), //???
array('1.000,3', true), //???
);
}
Using this new logic:
$locale = $this->locale;
$fmt = new NumberFormatter($locale, NumberFormatter::DECIMAL);
if (intl_is_failure($fmt->getErrorCode())) {
throw new Exception\InvalidArgumentException("Invalid locale string given");
}
$parsedFloat = $fmt->parse($value);
if (intl_is_failure($fmt->getErrorCode())) {
$this->error(self::NOT_FLOAT);
return false;
}
$decimalSep = $fmt->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
$groupingSep = $fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
$valueFiltered = str_replace($groupingSep, '', $value);
$valueFiltered = str_replace($decimalSep, '.', $valueFiltered);
if (strval($parsedFloat) !== $valueFiltered) {
$this->error(self::NOT_FLOAT);
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment