469,366 Members | 2,407 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,366 developers. It's quick & easy.

math error

The code:

$weight = 5.03;
my $gross = int($weight);
my $frac = $weight - $gross;
print "$frac\n";

Should print the decimal part of .03, but gives this instead:

0.0300000000000002

What am I doing wrong?

Marshall
Aug 23 '05 #1
2 2605
In article <43***************@king-cart.com>, Marshall Dudley
<md*****@king-cart.com> wrote:
The code:

$weight = 5.03;
my $gross = int($weight);
my $frac = $weight - $gross;
print "$frac\n";

Should print the decimal part of .03, but gives this instead:

0.0300000000000002

What am I doing wrong?


You are expecting the number 5.03 to be stored precisely in
floating-point binary format, which it cannot.

See 'perldoc -q numbers'

Use
printf "%.2f\n", $frac;

FYI: this newsgroup is defunct. Try comp.lang.perl.misc in the future.
----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
Aug 23 '05 #2
Marshall Dudley wrote:
[code snipped]
Should print the decimal part of .03, but gives this instead:

0.0300000000000002

What am I doing wrong?


Using floating point arithmetic for precision calculations?
You must have missed the first lesson in computer numerics: "Thou shalt not
use floating point if expecting accurate results."

Anyway, see "perldoc -q 999" and DejaNews/Google for numerous discussions
about this topic.

jue
Aug 24 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by M. Lavasani | last post: by
reply views Thread by Jussi Mononen | last post: by
4 posts views Thread by Robert Scheer | last post: by
17 posts views Thread by cwdjrxyz | last post: by
2 posts views Thread by mbelew | last post: by
11 posts views Thread by Sambo | last post: by
4 posts views Thread by pdlemper | last post: by
5 posts views Thread by aguirre.adolfo | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.