php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #80241 Casts double to int
Submitted: 2020-10-15 14:30 UTC Modified: 2020-10-15 14:33 UTC
From: dmitrijlin9 at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.4.11 OS: Windows 10
Private report: No CVE-ID: None
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
46 - 2 = ?
Subscribe to this entry?

 
 [2020-10-15 14:30 UTC] dmitrijlin9 at gmail dot com
Description:
------------
I'm trying to cast double variable to int, but i have wrong answer

Test script:
---------------
$a = '2166.99';
echo (int)($a *100);

Expected result:
----------------
216699

Actual result:
--------------
216698


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-10-15 14:33 UTC] girgias@php.net
-Status: Open +Status: Not a bug
 [2020-10-15 14:33 UTC] girgias@php.net
Floating point values have a limited precision. Hence a value might
not have the same string representation after any processing. That also
includes writing a floating point value in your script and directly
printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE
754 is, read this:
http://www.floating-point-gui.de/

Thank you for your interest in PHP.


 [2020-10-15 14:35 UTC] danack@php.net
fyi, using https://github.com/Danack/FloatHex and running `echo float_compare(216699, 2166.99 * 100);` it's possible to see the rounding error between these two numbers is a single bit.

┌──────┬─────────────┬──────────────────────────────────────────────────────┐
│ Sign │ Exponent    │ Mantissa                                             │
│    0 │ 10000010000 │ 1010011100111101100000000000000000000000000000000000 │
│    0 │ 10000010000 │ 1010011100111101011111111111111111111111111111111111 │
│    - │ ----------- │ ----------------xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx │
└──────┴─────────────┴──────────────────────────────────────────────────────┘
 [2020-10-15 14:40 UTC] dmitrijlin9 at gmail dot com
Ok, but why if we have variable $a = '5.99' the answer is correct?
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Oct 31 23:01:28 2024 UTC