LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   awk: Convert large number to human readable (Mb,Gb, TB, PB) / round up/down results (http://www.linuxquestions.org/questions/programming-9/awk-convert-large-number-to-human-readable-mb-gb-tb-pb-round-up-down-results-4175451244/)

 Rava 02-22-2013 03:39 AM

awk: Convert large number to human readable (Mb,Gb, TB, PB) / round up/down results

I read all posts of this thread http://www.linuxquestions.org/questi...gb-etc-597921/
Quote:
 Originally Posted by grail (Post 4070108) Code: #!/usr/bin/awk -f BEGIN{        x = 456456         split("B KB MB GB TB PB",type)         for(i=5;y < 1;i--)             y = x / (2**(10*i))         print y type[i+2] }
Now, I wanted the above as script, and it was wikipedia that gave me the info. xD
Code:

#!/usr/bin/awk -f

BEGIN{        x = ARGV[1]

split("B KB MB GB TB PB",type)

for(i=5;y < 1;i--)
y = x / (2**(10*i))

print y " " type[i+2]
}

(I also added a whitespace)

My example number is "3203368960", and my script gave me
Code:

2.98337 GB
Now... all that is still needed is a way to have the script round up/round down the calculation and cut all behind the dot values but the first 2, in my example that would be:
Code:

2.98 GB
If the result was
Code:

2.98533 GB
instead, the rounding should have been
Code:

2.99 GB
of course. Any ideas how this can be done with awk?

 linosaurusroot 02-22-2013 04:12 AM

I think you want the format options of printf(). http://linux.die.net/man/3/printf

printf("%.2f %s\n", number, unit);

 druuna 02-22-2013 04:14 AM

Try changing this line print y " " type[i+2] to this:
Code:

printf("%.2f %s\n",y,type[i+2])
Also have a look at these 2:
- 5.5 Using printf Statements for Fancier Printing
- 13.2.3 Rounding Numbers

EDIT: Beaten to it ;)

 Rava 02-23-2013 04:37 AM

Thanks a lot to you! *hands over virtual TUX plushies*

Just for the record and for the ones lurking here / ones that find the thread via forum search or internet search, this is the finale version of the script:

Code:

#!/usr/bin/awk -f

BEGIN{        x = ARGV[1]

split("B KB MB GB TB PB",type)

for(i=5;y < 1;i--)
y = x / (2**(10*i))

printf("%.2f %s\n",y,type[i+2])
}

 All times are GMT -5. The time now is 06:39 PM.