develooper Front page | perl.beginners | Postings from January 2002

Re: decimal point

Thread Previous | Thread Next
From:
Curtis Poe
Date:
January 28, 2002 16:36
Subject:
Re: decimal point
Message ID:
20020129003654.67398.qmail@web9104.mail.yahoo.com

--- Leon <eventualdeath@yahoo.com> wrote:
> Try this;
> my $total = "4536233";
> $total =~s/(.+)(\d{2})/$1.$2/;
> print $total;

Ooh... I'd be careful of a regex like that.

$ perl -e '
> $foo = "I told you 100 times not to do that :)";
> $foo =~ s/(.+)(\d{2})/$1.$2/;
> print $foo'
I told you 1.00 times not to do that :)

You're slurping up everything in there!  Also, if you *know* that you only have digits, you can
get mysterious failures.  I'd use a regex like this:

    $foo =~ s/^(\d*)\d{2}$/$1./;

However, even then, a regex is overkill.  sprintf seems like a better choice:

$ perl -e '
> my $num = "12345";
> $num /= 100;
> printf "%0.2f", $num'
123.45

Cheers,
Curtis "Ovid" Poe


=====
"Ovid" on http://www.perlmonks.org/
Someone asked me how to count to 10 in Perl:
push@A,$_ for reverse q.e...q.n.;for(@A){$_=unpack(q|c|,$_);@a=split//;
shift@a;shift@a if $a[$[]eq$[;$_=join q||,@a};print $_,$/for reverse @A

__________________________________________________
Do You Yahoo!?
Great stuff seeking new owners in Yahoo! Auctions! 
http://auctions.yahoo.com

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About