bug #21769 [Form] Improve rounding precision (foaly-nr1)
This PR was squashed before being merged into the 2.7 branch (closes #21769).
Discussion
----------
[Form] Improve rounding precision
| Q | A
| ------------- | ---
| Branch? | 2.7
| Bug fix? | yes
| New feature? | no
| BC breaks? | no
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets | 21734
| License | MIT
| Doc PR |
For full details see https://github.com/symfony/symfony/issues/21734 from https://github.com/symfony/symfony/issues/21734#issuecomment-282552802 onwards.
Excerpt:
```php
$number = floor(37.37*100); // double(3736)
var_dump($number);
$number = floor(bcmul(37.37, 100)); // double(3737)
var_dump($number);
```
From http://php.net/manual/en/language.types.float.php#language.types.float:
> Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....
>
> So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.
Commits
-------
e50804cef4
[Form] Improve rounding precision
This commit is contained in:
commit
058121819c
@ -266,7 +266,8 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface
|
||||
if (null !== $this->precision && null !== $this->roundingMode) {
|
||||
// shift number to maintain the correct scale during rounding
|
||||
$roundingCoef = pow(10, $this->precision);
|
||||
$number *= $roundingCoef;
|
||||
// string representation to avoid rounding errors, similar to bcmul()
|
||||
$number = (string) ($number * $roundingCoef);
|
||||
|
||||
switch ($this->roundingMode) {
|
||||
case self::ROUND_CEILING:
|
||||
|
@ -307,6 +307,8 @@ class NumberToLocalizedStringTransformerTest extends TestCase
|
||||
array(1, '123,44', 123.4, NumberToLocalizedStringTransformer::ROUND_DOWN),
|
||||
array(1, '-123,45', -123.4, NumberToLocalizedStringTransformer::ROUND_DOWN),
|
||||
array(1, '-123,44', -123.4, NumberToLocalizedStringTransformer::ROUND_DOWN),
|
||||
array(2, '37.37', 37.37, NumberToLocalizedStringTransformer::ROUND_DOWN),
|
||||
array(2, '2.01', 2.01, NumberToLocalizedStringTransformer::ROUND_DOWN),
|
||||
// round halves (.5) to the next even number
|
||||
array(0, '1234,6', 1235, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
|
||||
array(0, '1234,5', 1234, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
|
||||
|
Reference in New Issue
Block a user