Re: [MacPerl-Porters] fiddling around with a commify sub, and found this.. bug?
[email protected] (Chris Nandor) Sat, 17 Nov 2001 07:47:13 -0500
| Newsgroups | perl.macperl.porters |
|---|---|
| Message-ID | <p05100301b81c09858426@[10.0.1.177]> |
At 02:07 -0500 2001.11.17, Scott R. Godin wrote:
># and just to be sure...
>print scalar 87264867324.723474;
>
># is scalar supposed to round ?
It does the same thing with or without scalar().
>87,264,867,324.7235
>87264867324.7235
Perl does a lot of rounding when necessary. If you need to preserve
numbers exactly, you can do a couple of things. First, you can quote them.
If you are treating it as a string, which you are, then no need to do
arithmetic. When you write the number, it is converted to a number as it
is saved into a perl variable. So when you do:
print 87264867324.723474;
->87264867324.7235
what happens is it converts that thing into a Perl number value, and then
prints it. In that conversion, it is rounded. So you can do:
print "87264867324.723474";
->87264867324.723474
You can also look into using Math::BigFloat. Consider:
$num = "87264867324.723474";
print $num+0;
->87264867324.7235
That converts it to a string, so you have the full number stored in the
Perl value, but then it does math on it, and it rounds it again. You can
put a stop to such "nonsense" with a special standard module:
use Math::BigFloat;
$num = Math::BigFloat->new("87264867324.723474");
print $num+0;
->87264867324.723474
Yay.
Note that you still need to quote the number when it is passed to the new()
method, for the same reason you need to quote it when printing it by
itself. Perl will convert it to a number before putting it in the special
Perl number value.
However, since you are not doing math, a simple quoting in your example
script will solve the problem.
Also, look in perlfaq5 for examples of a commify() function.
--
Chris Nandor [email protected] http://pudge.net/
Open Source Development Network [email protected] http://osdn.com/