Skip to content

Commit

Permalink
Adding support for environments that have a system locales with diffe…
Browse files Browse the repository at this point in the history
…rent decimal separator (#20)
  • Loading branch information
Mykhailo Sulyma authored and BenMorel committed Feb 12, 2019
1 parent df1eca1 commit 510f506
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/BigNumber.php
Expand Up @@ -61,7 +61,13 @@ public static function of($value) : BigNumber
return new BigInteger((string) $value);
}

$value = (string) $value;
if (is_float($value)) {
$locData = localeconv();

$value = str_replace([$locData['thousands_sep'], $locData['decimal_point']], ['', '.'], (string) $value);
} else {
$value = (string) $value;
}

if (\preg_match(self::PARSE_REGEXP, $value, $matches) !== 1) {
throw new NumberFormatException(\sprintf('The given value "%s" does not represent a valid number.', $value));
Expand Down
26 changes: 26 additions & 0 deletions tests/BigDecimalTest.php
Expand Up @@ -163,6 +163,32 @@ public function providerOf()
];
}

/**
* @dataProvider providerOfLocales
*
* @param string $locale
*/
public function testOfValueInDifferentLocales(string $locale): void
{
$originalLocale = setlocale(LC_NUMERIC, '0');
setlocale(LC_NUMERIC, $locale);

$this->assertEquals(2.5, BigDecimal::of(5/2)->toFloat());

setlocale(LC_NUMERIC, $originalLocale);
}

/**
* @return array
*/
public function providerOfLocales(): array
{
return [
['en_US.UTF-8'],
['de_DE.UTF-8'],
];
}

/**
* @dataProvider providerOfInvalidValueThrowsException
* @expectedException \Brick\Math\Exception\NumberFormatException
Expand Down

0 comments on commit 510f506

Please sign in to comment.