zumba/json-serializer

setlocale() issue for floats

wrey75 opened this issue · 2 comments

When you change the locale (using, for example, setlocale(LC_ALL, "fr_FR") in your PHP code), the conversion of floats are made in the locale (for France, using "," instead of "." for decimal point). Then if the variable $preserveZeroFractionSupport is set to true, there is an encoding issue.

I found this workaround forcing the formatting only in specific cases:

            if (!$this->preserveZeroFractionSupport && is_float($value) && abs($value) < 1e+10 && abs($value) > 0.01 ) {
                // Because the PHP bug #50224, the float numbers with no
                // precision numbers are converted to integers when encoded
                // Notice the following will not be sensible to locale.
                $value = static::FLOAT_ADAPTER . '(' . number_format($value, 6, ".", "" ) . ')';
            }

@wrey75 Thanks for reporting it.

After analyzing the ways to solve I ended choosing the one from the PR #18. The goal of that if is just to identify if the float number has a decimal value. That means if the value is converted without any decimal (just numbers), we need to append the .0.

Using the number_format cause some numbers to lose precision. Ie 1.0e-11 was being converted to 0.0, 1.999999999999 to 2.0, etc.

Let me know what do you think about the solution using ctype_digit.

Much better than my proposal. ctype_digit does the job.