Re: Proposal: change precision for output functions

php.internals

Legale Legage

7 years ago
I think your solution by changing precision is not good enough because float summation is still not working properly. <?php var_dump(0.1 + 0.7); returns: 0.7999999999 expected: 0.8 On Jan 7, 2019 7:17 PM, Semen Dubina <php@sam002.net> wrote: > > > 07.01.2019, 20:24, "Thomas Bley" <mails@thomasbley.de>: > > > > Hello, > > > > good point, having: > > > > echo ini_get('precision') . PHP_EOL; > > echo ini_get('serialize_precision') . PHP_EOL; > > echo json_encode(array('price' => round('45.99', 2))) . PHP_EOL; > > echo (0.1+0.7), json_encode(0.1+0.7) . PHP_EOL; > > > > gives (https://3v4l.org/ldgo8): > > > > Output for 7.1.0 - 7.3.0 > >     14 > >     -1 > >     {"price":45.99} > >     0.80.7999999999999999 > > > > Output for 5.3.6 - 5.6.38, 7.0.0 - 7.0.33 > >     14 > >     17 > >     {"price":45.99} > >     0.80.8 > > > > what is the preferred way to upgrade from php 5.6 to 7.x in order to get the same results? > > > > Regards > > Thomas > > > > Force 'serialize_precision': https://3v4l.org/coaWm > But remember - a float is not suitable for output. You need rounded and formatted manually. > > P.S. Try with JS: `JSON.stringify(0.1+0.7);` > > -- Semen V. Dubina https://sam002.net/ > > -- > PHP Internals - PHP Runtime Development Mailing List > To unsubscribe, visit: http://www.php.net/unsub.php >

Semen Dubina

7 years ago
> 07.01.2019, 22:17, "Legale.legale" <legale.legale@gmail.com>: > I think your solution by changing precision is not good enough because float summation is still not working properly. > > <?php > var_dump(0.1 + 0.7); > > returns: > > 0.7999999999 > > expected: 0.8 >
Hi! If you are about the proposal, then '0.1 + 0.7 !== 0.8'. Why you expected 0.8? Check, plz: https://3v4l.org/Ughn2  -- Semen V. Dubina https://sam002.net/

Lauri Kenttä

7 years ago
On 2019-01-07 21:17, Legale.legale wrote:
> I think your solution by changing precision is not good enough because > float summation is still not working properly. > > <?php > var_dump(0.1 + 0.7); > > returns: > > 0.7999999999 > > expected: 0.8
As you may know, most computers use binary numbers. This applies to floating-point values as well. They have a limited number of binary digits. Many base-10 numbers cannot be expressed exactly in base-2 with limited number of digits. When you write 0.1 + 0.7, what you get (with double-precision floats) is closer to 0.1000000000000000055511 + 0.6999999999999999555911 = 0.7999999999999999333866. This is expected and proper and well known. You have to use formatting functions like number_format if you need neatly rounded base-10 output. There are also a lot of libraries for precise base-10 calculations. They will be a lot slower than native binary floating-point calculations, though. Regards, Lauri Kenttä