### Perl rounder...

by abaxaba (Hermit)
 on Apr 08, 2002 at 21:05 UTC Need Help??
 Description: Just a little hack to round numbers. Strips leading zeros, pads the precision of you want more places then your decimal length...
```
#!/usr/bin/perl

main();
sub main
{
my (\$num,\$prec)=@ARGV;
my (\$mant,\$dec) = split (/\./,\$num);
\$dec=\$dec?\$dec:"0";
\$mant=~s/^(-?)0+/\$1/;
\$mant=!\$mant?0:\$mant;
(\$prec,\$dec)=\$prec==0?(\$prec,undef):(\$prec+1,substr(\$dec,0,\$prec+1
+));
\$dec=~s/\$dec/length(\$dec)<\$prec?\$dec."0"x(\$prec-length(\$dec)):\$dec
+/e;
my \$round = join ("",(\$mant,length(\$dec)?".":"",round(\$dec)));
output (\$round);
}
sub round
{
my \$dec=shift;
\$dec=~s/(\d)(\d)\$/\$2<5?\$1:\$1+1/e;
\$dec;
}

sub output
{
print "Round = ",shift,"\n";
}

```
Replies are listed 'Best First'.
Re: Perl rounder...
by maverick (Curate) on Apr 08, 2002 at 22:21 UTC
Sorry dude, it's already been done.
```printf("%.\$ARGV[1]f\n",\$ARGV[0]);
printf takes a sting that describes what you want to print. In your case a floating point number (f) with a precision that you specify as the second arg (\$ARGV[1]) using the value in \$ARGV[0]

/\/\averick
OmG! They killed tilly! You *bleep*!!

Re: Perl rounder...
by gav^ (Curate) on Apr 08, 2002 at 22:36 UTC

Create A New User
Node Status?
node history
Node Type: snippet [id://157555]
help
Chatterbox?
 Eily got the Cowboy message [Your Mother]: I prefer palatial fricatives. [Your Mother]: I'm headed out west, sucker. [Lotus1]: the west is the best, get here we'll do the rest LanX chjuman ! [Eily]: do you pronunce that /xju:mən/ then ? [Eily]: that's not what I'd call a silent h :) [LanX]: [Your Mother]: Just Another Perl 'Acker.

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (15)
As of 2017-03-27 17:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should Pluto Get Its Planethood Back?

Results (320 votes). Check out past polls.