On 22/08/2015 17:38, Alexander Kapshuk wrote: > On Sat, Aug 22, 2015 at 4:26 PM, hw <h...@gartencenter-vaehning.de> wrote: >> >> Hi, >> >> I have the following in a perl script: >> >> >> if ($a != $b) { >> print "e: '$a', t: '$b'\n"; >> } >> >> >> That will print: >> >> e: '69.99', t: '69.99' >> >> >> When I replace != with ne (if ($a ne $a) {), it doesn't print. >> >> >> Is that a bug or a feature? And if it's a feature, what's the explanation? >> >> And how do you deal with comparisions of variables when you get randomly >> either correct results or wrong ones? It's randomly because this statement >> checks multiple values in the script, and 69.99 is the only number showing >> up yet which isn't numerically equal to itself (but equal to itself when >> compared as strings). >> > > Perl Cookbook, 2nd edition, suggests these two approaches to comparing > floats for equality. > (1). Use sprintf to format the numbers to a certain number of decimal > places, then compare the resulting strings. > (2). Alternatively, store the numbers as integers by assuming the decimal > place.
A good way to demonstrate just how problematic floats can be is to point out that floats are banned in the linux kernel for exactly this reason. Integers only. -- Alan McKinnon alan.mckin...@gmail.com