Convert numbers to SI notation

$ awk '{ split(sprintf("%1.3e", $1), b, "e"); p = substr("yzafpnum_kMGTPEZY", (b[2]/3)+9, 1); o = sprintf("%f", b[1] * (10 ^ (b[2]%3))); gsub(/\./, p, o); print substr( gensub(/_[[:digit:]]*/, "", "g", o), 1, 4); }' < test.dat
converts any number on the 'stdin' to SI notation. My version limits to 3 digits of precious (working with 10% resistors).
Sample Output
1
10
100
1k23
10k0
100k
1M00
24k5
4k54
2P35
0m34
0n35

2
By: mungewell
2009-07-22 16:54:14

These Might Interest You

What Others Think

awk.exe?
RickDeckardt · 465 weeks and 2 days ago
More readable version (with biasing for m,u,n,..) -- { split(sprintf("%1.3e", $1), bits, "e"); if (bits[2] < 0) { bits[1] *= 1000; bits[2] -= 3; } prefix = substr("yzafpnum_kMGTPEZY", (bits[2]/3)+9, 1) output = sprintf("%f", bits[1] * (10 ^ (bits[2]%3))); gsub(/\./, prefix, output); print substr( gensub(/_[[:digit:]]*/, "", "g", output), 1, 4); } --
mungewell · 465 weeks and 2 days ago
yeah yeah cygwin you know... ;-)
mungewell · 465 weeks and 2 days ago
There has GOT to be a better way to do this
linuxrawkstar · 465 weeks and 2 days ago
I wish I could find a better way, spent about an hour googling. Better version: -- { split(sprintf("%-1.2e", $1), bits, "e"); prefix = substr("yzafpnum.kMGTPEZY", (bits[2]/3)+9, 1) output = sprintf("%f", bits[1] * (10 ^ ((bits[2]+18)%3))); gsub(/\./, prefix, output); print gensub(/\.$/, "", "g", gensub(/[0]*$/, "", "g", output)); } --
mungewell · 465 weeks and 2 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: