From 510f506185d4c988f97180426ec80fb3dbf51e04 Mon Sep 17 00:00:00 2001 From: Mykhailo Sulyma Date: Tue, 12 Feb 2019 12:40:15 +0200 Subject: [PATCH] Adding support for environments that have a system locales with different decimal separator (#20) --- src/BigNumber.php | 8 +++++++- tests/BigDecimalTest.php | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/BigNumber.php b/src/BigNumber.php index 6fbafd6..9a2f110 100644 --- a/src/BigNumber.php +++ b/src/BigNumber.php @@ -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)); diff --git a/tests/BigDecimalTest.php b/tests/BigDecimalTest.php index e27289d..830518c 100644 --- a/tests/BigDecimalTest.php +++ b/tests/BigDecimalTest.php @@ -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