[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] A parseing we will go....



At 7:53 AM -0500 12/14/99, Allan Greenier wrote:
>Hi all,
>
>     I'm curious to see how others might solve a little coding problem I
>worked on this week.
>You have a number, floating point. Could be
>
>001254.6987 or 0.2500 or 012.685000
>There's any number of leading or trailing zeroes before and after the
>decimal I want to get rid of.
>If they are all zeroes I need 1.0 instead of 1.00000 and 0.1 instead of
>00000.1. Otherwise I just need to lop off the leaders or trailers.
>Any takers?
>A direct cc would be appreciated.


It seems you want to get rid of all leading zeros if there's anything 
else on the left, all leading zeros but one if there are only zeros, 
and all but one trailing zeros on the right if there are only zeros, 
all trailing zeros if there is anything else.  I'd use a couple of 
regexps:

s/^0*(\d+\.\d*)/$1/;
s/(\d+\.\d+?)0*$/$1/;

i.e.:

#!perl

@numbers = qw(001254.6987 0.2500 012.685000 1.00000 0000.2500  012.68005000);

for (@numbers) {
   s/^0*(\d+\.\d*)/$1/;
   s/(\d*\.\d+?)0*$/$1/;
   print $_,"\n";
}
__END__

Of course, it's too early in the morning to think of all the special 
cases (I tried a few), and the fancy "detect a number" regexs in the 
parenthesis aren't really necessary, I suppose.

You could also just use a %g format with printf, but you don't say if 
the numbers might get large enough to switch to exponential notation, 
and %g will even get rid of the decimal at times.

>
>Allan
>
>Allan Greenier
>AutoScript Applcations
>
>agreenier@snet.net
>http://www.geocities.com/~autoscript
>

--
Paul Schinder
schinder@pobox.com

# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org