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

Re: decimal point

Thread Previous | Thread Next
Curtis Poe
January 28, 2002 16:36
Re: decimal point
Message ID:

--- Leon <> 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'

Curtis "Ovid" Poe

"Ovid" on
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!

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About