note 115850 added to language.types.float

From: Date: Fri, 03 Oct 2014 14:35:33 +0000
Subject: note 115850 added to language.types.float
Groups: php.notes 
Request: Send a blank email to php-notes+get-200577@lists.php.net to get a copy of this message
I've just come across this issue with floats when writing a function for pricing. When converting from string to a float, with 2 digits of precision, the issue with comparing floats can pop up and give inconsistent results due to the conversion process. An easier way rather than relying on the mentioned epsilon method is to use number_format (at least for me as I'll remember it!). Example function that can return an unexpected result: if((float)$a == (float)$b) { echo true; } else { echo false; } echo's false in this example. Using number format here to trim down the precision (2 point precision being mostly used for currencies etc, although higher precisions should be correctly catered for by number_format), will return an expected result: if(number_format((float)$a, 2) == number_format((float)$b, 2)) { echo true; } else { echo false; } Correctly echo's true. ---- Server IP: 72.52.91.14 Probable Submitter: 46.18.218.130 ---- Manual Page -- http://php.net/manual/en/language.types.float.php Edit -- https://master.php.net/note/edit/115850 Del: integrated -- https://master.php.net/note/delete/115850/integrated Del: useless -- https://master.php.net/note/delete/115850/useless Del: bad code -- https://master.php.net/note/delete/115850/bad+code Del: spam -- https://master.php.net/note/delete/115850/spam Del: non-english -- https://master.php.net/note/delete/115850/non-english Del: in docs -- https://master.php.net/note/delete/115850/in+docs Del: other reasons-- https://master.php.net/note/delete/115850 Reject -- https://master.php.net/note/reject/115850 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#200577) next »