Bug #75644 [Opn->Wfx]: round(362.42499999999995, 2) gives incorrect result

From: Date: Fri, 09 Jul 2021 15:40:17 +0000
Subject: Bug #75644 [Opn->Wfx]: round(362.42499999999995, 2) gives incorrect result
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-234937@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=75644&edit=1 ID: 75644 Updated by: cmb@php.net Reported by: markamery at btinternet dot com Summary: round(362.42499999999995, 2) gives incorrect result -Status: Open +Status: Wont fix Type: Bug Package: Math related Operating System: Ubuntu PHP Version: 7.1.12 -Assigned To: +Assigned To: cmb Block user comment: N Private report: N New Comment: TIL that PHP uses an elaborate rounding algorithm[1], and due to this, you get the wrong result. Changing this would require an RFC (and the RFC author would need to figure out a way how to support other modes than HALF_EVEN), but fortunately the float to string conversion has not been "fixed", so you can use e.g. printf() to get the desired results. Anyhow, while rounding to two decimals might have practical use cases, monetary arithmetic is not one of them. [1] <https://wiki.php.net/rfc/rounding> Previous Comments: ------------------------------------------------------------------------ [2017-12-06 22:47:34] markamery at btinternet dot com Description: ------------ Even though 362.42499999999995 is less than 362.425 (i.e. the internally-stored IEEE-754 representation of 362.42499999999995 has a value less than 362.425), round(362.42499999999995, 2) gives 362.43 It should give 362.42 Test script: --------------- <?php $x = 362.42499999999995; echo $x . "\n"; echo round($x, 2) . "\n"; ini_set('precision', 999); echo $x . "\n"; echo round($x, 2) . "\n"; Expected result: ---------------- 362.425 362.42 362.424999999999954525264911353588104248046875 362.42000000000001591615728102624416351318359375 Actual result: -------------- 362.425 362.43 362.424999999999954525264911353588104248046875 362.43000000000000682121026329696178436279296875 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=75644&edit=1

« previous php.bugs (#234937) next »