avram: (Default)
[personal profile] avram

Are 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?

(no subject)

Date: 2010-03-08 03:54 pm (UTC)
From: [identity profile] stormsweeper.livejournal.com
I'm fairly certain you can use awk.

(no subject)

Date: 2010-03-11 05:53 pm (UTC)
ext_23444: This is a multi-spectrum false-color image of the Sun. (Default)
From: [identity profile] perldiver.livejournal.com
$ perl -le '$_ = shift; s/,//; $_ += 0; print;' 5e6
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 02:12 am (UTC)
ext_23444: This is a multi-spectrum false-color image of the Sun. (Default)
From: [identity profile] perldiver.livejournal.com
You're better off learning to use Perl. It can do everything awk can do and more, plus it's actually a marketable skill in and of itself.

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;
}

April 2017

S M T W T F S
      1
2345678
9101112131415
16171819202122
23242526272829
30      

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags