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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: dmitrijlin9 at gmail dot com
New email:
PHP Version: OS:

 

 [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

Add a Patch

Pull Requests

Add a Pull Request

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: Mon Apr 29 06:01:29 2024 UTC