Re: decimal placement
by Chady (Priest) on Mar 26, 2001 at 01:35 UTC
|
$n = 13.2;
$n2 = sprintf("%.2f", $n);
print $n2; # should print 13.20
He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life. | [reply] [d/l] [select] |
Re: decimal placement
by arturo (Vicar) on Mar 26, 2001 at 01:39 UTC
|
There's a printf function, as in C, and a sprintf function too.
So
printf ("%3.2f", $num);
Should get you what you're after.
HTH
Philosophy can be made out of anything. Or less -- Jerry A. Fodor | [reply] [d/l] |
Re: decimal placement
by knight (Friar) on Mar 26, 2001 at 01:40 UTC
|
The usual way to print floating-point values
rounded and padded to two decimal places:
printf "%.02f\n", $float
Or, if you need to use a so-formatted string representation of your floating point number for something else:
$string = sprintf "%.02f", $float
Read up on s?printf in the doc for a full
description of what you can do with the formatting string
(the %.02f part of the above examples).
| [reply] [d/l] [select] |
Re: decimal placement
by lachoy (Parson) on Mar 26, 2001 at 03:59 UTC
|
In addition to s/printf, you might also
want to check out Number::Format, which deals
with localization issues as well as other formats
like bytes/kilobytes/megabytes, money, etc.
Chris
M-x auto-bs-mode
| [reply] [d/l] |
|
|
This may be seriously unfair, but the two aspects of
Perl's behaviour
(to my eyes bugs) that I dislike most I learned tracking
down bugs in Number::Format.
The first was the infamous "my $foo if 0;", the other is
the fact that $_ is the same in all namespaces, so call a
function in a map and it can wipe out your input array
- even if the module is in another namespace.
Not bad for a module that I don't even use! (Co-workers
discovered it and used it. Personally I would have been
perfectly happy with what sprintf offers...)
| [reply] |
Re: decimal placement
by Anonymous Monk on Mar 26, 2001 at 01:42 UTC
|
Why are you all using double quotes in your printf formats? You aren't using any interpolation, so you should use single quotes instead (it's faster because it dosen't have to check for interpolations) | [reply] |
|
|
| [reply] |
|
|
| [reply] |
|
|
| [reply] |
|
|
Re: decimal placement
by Fingo (Monk) on Mar 26, 2001 at 02:52 UTC
|
If you have many numbers, format may be a good option. | [reply] |