http://qs321.pair.com?node_id=587722


in reply to Re: "Commifying" a number
in thread "Commifying" a number

I agree that this is a case for sexeger.

I ran your 'commify' sub through BrowserUk's commify tester above, and noticed that it could use a zero-width positive lookahead assertion (?=\d+) instead of the direct match of a digit after the (\d{3})(\d) (that almost works, but leaves some commification with 4 digits between comma's). And, since it uses a lookahead, the final $2 can be removed from the substitution. Here's my version of commify sexeger...

sub commify { local $_ = reverse shift; /\./g; s/\G(\d{3})(?=\d+)/$1,/g; return scalar reverse $_; }

Here's the results with the updated sexeger:

$ perl commify.pl -0.0001234567890 commified becomes -0.000123456789 -0.0012345678900 commified becomes -0.00123456789 -0.0123456789000 commified becomes -0.0123456789 -0.1234567890000 commified becomes -0.123456789 -1.2345678900000 commified becomes -1.23456789 -12.3456789000000 commified becomes -12.3456789 -123.4567890000000 commified becomes -123.456789 -1234.5678900000000 commified becomes -1,234.56789 -12345.6789000000008 commified becomes -12,345.6789 -123456.7890000000043 commified becomes -123,456.789 -1234567.8899999998976 commified becomes -1,234,567.89 -12345678.9000000003725 commified becomes -12,345,678.9 -123456789.0000000000000 commified becomes -123,456,789 -1234567890.0000000000000 commified becomes -1,234,567,890 -12345678900.0000000000000 commified becomes -12,345,678,900 -123456789000.0000000000000 commified becomes -123,456,789,000 -1234567890000.0000000000000 commified becomes -1,234,567,890,000 -12345678900000.0000000000000 commified becomes -12,345,678,900,000 -123456789000000.0000000000000 commified becomes -123,456,789,000,000 -1234567890000000.0000000000000 commified becomes -1.23456789e+15

Cheers!

--
hiseldl
What time is it? It's Camel Time!

Replies are listed 'Best First'.
Re^3: "Commifying" a number
by Aristotle (Chancellor) on Dec 10, 2006 at 21:29 UTC

    that almost works

    Nice catch; should have been obvious when I wrote it.

    Btw, your lookahead assertion needn’t be quantified: (?=\d) will work exactly as (?=\d+) does, but won’t waste time matching extra digits.

    Makeshifts last the longest.

      Here is a version without using reverse function. sub commify { (my $number = shift) =~ s/\G(-?)(\d{1,3})(?=(?:\d\d\d)+(?:\.|$))/$1$2,/g; return $number; } Manikanthan Velayutham programmed to think BIG
        My earlier post did not appear properly.
        sub commify { (my $number = shift) =~ s/\G([+|-]?)(\d{1,3})(?=(?:\d\d\d)+(?:\.|$ +))/$1$2,/g; return $number; }
        Manikanthan Velayutham

        programmed to think BIG