how sub can have 2 decimal numbers only?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

my \$usdTotal = \$Total / 6.2;

when Perl calculate it I hzave result like \$usdTotal = 120.2435445466

but I need 120.24 only (2 digits after dot..)

how I can do it?

Re: how sub can have 2 decimal numbers only?

my \$usdTotal = sprintf "%.2f",\$Total/6.2;

or

my \$usdTotal = int(\$Total/6.2*100)/100

thanks!

Re: how sub can have 2 decimal numbers only?

Note that the latter still won't necessarily give you a value of
exactly 120.24, because that value cannot be represented exactly in
binary floating-point (just as 1/3 cannot be represented exactly in
decimal).

% cat foo
#!/usr/bin/perl -w

use strict;

my \$Total = 745.51;
my \$usdTotal;

\$usdTotal = \$Total / 6.2;
print "\$usdTotal (not rounded)     = \$usdTotal\n";

\$usdTotal = int(\$Total/6.2*100)/100;
print "\$usdTotal (rounded)         = \$usdTotal\n";
printf "\$usdTotal (extra precision) = %.30f\n", \$usdTotal;
% ./foo
\$usdTotal (not rounded)     = 120.243548387097
\$usdTotal (rounded)         = 120.24
\$usdTotal (extra precision) = 120.239999999999994884092302527279

--
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst
San Diego Supercomputer Center             <*>  <http://users.sdsc.edu/~kst
We must do something.  This is something.  Therefore, we must do this.

Re: how sub can have 2 decimal numbers only?

also, i forgot to take care of any rounding.  ignoring any precision
errors, i should have said

\$usdTotal=int((\$Total/6.2*100)+.5)/100;

but you are correct about the precision errors.  i forgot about that.
i always do my conversions with sprintf, so i never have to worry about
that.

Re: how sub can have 2 decimal numbers only?

perldoc -q round

Does Perl have a round() function?  What about ceil() and floor()?
Trig functions?

--
Tad McClellan                          SGML consulting
Fort Worth, Texas

Re: how sub can have 2 decimal numbers only?

perldoc -f sprintf

Please consult the documentation first.

Sinan
--
(reverse each component and remove .invalid for email address)

comp.lang.perl.misc guidelines on the WWW: