Numeric string conversion
Mar. 7th, 2010 08:19 pmAre there any standard Unix command-line programs for converting number-like strings into numbers, and vice-versa? For example, converting…
- 1,000,000.00
- 1000000
- 1e6
- 1 * 10^6
…easily into one-another?
Are there any standard Unix command-line programs for converting number-like strings into numbers, and vice-versa? For example, converting…
…easily into one-another?
(no subject)
Date: 2010-03-08 03:54 pm (UTC)(no subject)
Date: 2010-03-11 05:53 pm (UTC)5000000
$
This won't handle 1 * 10^6, but that isn't a number, it's an expression. It will handle all of your other examples.
(no subject)
Date: 2010-03-13 01:54 am (UTC)I'm probably best off either learning to use awk, or cobbling together a library.
(no subject)
Date: 2010-03-13 02:12 am (UTC)You hadn't mentioned before that you wanted the numbers displayed with commas, but that's easy enough--there's a standard recipe for it in the Perl Cookbook:
$ perl conv.pl 5e6 500000 5.1992
5,000,000
500,000
5.1992
--- Contents of conv.pl:
#!/usr/bin/perl -l
while (defined ($_ = shift)) {
print commify( map {s/,//; $_ += 0; } $_ );
}
sub commify {
my $text = reverse $_[0];
$text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
return scalar reverse $text;
}