brick / math

Arbitrary-precision arithmetic library for PHP
MIT License
1.83k stars 78 forks source link

The given value ".1200" does not represent a valid number. #48

Closed JochemKlingeler closed 4 years ago

JochemKlingeler commented 4 years ago

It seems that decimal strings that do not start with an 0 char can not be parsed.

Example code

$a = BigDecimal::of('.1200')->serialize();
assert('1200:4' === $a);

Expected response

> true

Actual response

Brick/Math/Exception/NumberFormatException with message 'The given value ".1200" does not represent a valid number.'

Context

MS Sql Server returns money columns as strings, but does not prepend a 0 on values less then 1. I was hoping I could push these strings straight into BigDecimal.

Workaround

For now I am using this workaround:

if (is_string($value) && '.' === $value[0]) {
    $value = '0' . $value;
}
return BigDecimal::of($value);
BenMorel commented 4 years ago

Hi, although supporting leading zeros should not be technically challenging, I'm not sure it's a good idea to do so. I'd be curious to hear what others think about this!

BenMorel commented 4 years ago

After checking that Java's BigDecimal actually supports .123, as well as 123., I realized that it probably makes sense to support them as well, so I moved foward and added support for them!

Available right now in version 0.9.0. ✨