Created
June 27, 2012 15:42
-
-
Save cgmartin/3004926 to your computer and use it in GitHub Desktop.
Float and NumberFormatter oddity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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