Rounding and int

| | Comments (2) | TrackBacks (0)

Came across a curious fact today. Try this out:

$ perl -e "print int(2.07 * 100)"

You get 206 not 207. Same rounding down happens with 2.01 2.03 and 2.05. As perldoc -f int says,

You should not use this function for rounding

One alternative is to use sprintf, for instance:

my $num = sprintf("%.0f",(2.07 * 100)); # returns 207

Or even, from the command line:

perl -e 'printf("%.0f",(2.07 * 100))' # returns 207

Or you could use Math::Round and let that do the thinking for you. ;)

0 TrackBacks

Listed below are links to blogs that reference this entry: Rounding and int.

TrackBack URL for this entry: http://www.robbiebow.co.uk/mt/mt-tb.cgi/49

2 Comments

Tom Hukins said:

Yes, floating point numbers have a habit of naughtiness. I think I learned little else I still consider relevant from low-level programming.

Of course, Perl programmers should use CPAN's Math::* libraries for better precision.

I note your example uses 2 decimal places and I know what you do for a living. I prefer to store prices in pence, or the equivalent in whatever currency you use, instead of pounds, to avoid problems like this.

But then you get products that people typically buy in bulk with a unit cost of less than 1p, such as those electrical components we made a site for a couple of years ago.

Tough life programming, innit?

Happy birthday, belatedly, too.

Robbie Bow Author Profile Page said:

Storing in minor units is indeed optimal. Receiving data in minor units would be nice as well. Having all currencies adopt the sensible approach of the Japanese Yen which has no minor units at all would be the best approach, albeit not the cheapest.

Ta for the birthday wishes. I make good my threat to visit you sometime soon, mark my words.

Leave a comment

About this Entry

This page contains a single entry by Robbie Bow published on March 17, 2008 7:03 PM.

SOAP::Lite client for document/literal .NET web services was the previous entry in this blog.

uncaught exception: Permission denied to get property Window.App is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.21-en