Saturday, December 3, 2022

#1 2011-09-14 01:46:03 pm

Nigel Garvey
Moderator
From:: Warwickshire, England
Registered: 2002-11-20
Posts: 5588

Bytes to kilobytes, megabytes, etc., with suffix

I posted a byte-size converter many years ago, which may have been a reply to this one by Jonathan Nathan. But here's a new handler which allows the kilobyte-size convention to be specified (1024 or 1000) and the number of decimal places to which to round off the returned figure. The rounding follows the "point-five away from zero" convention and the results are only rounded to that number of places, not padded twith trailing zeros.

Applescript:

-- Convert a size in bytes to a convenient larger unit size with suffix. The 'KBSize' parameter specifies the number of units in the next unit up (1024 or 1000; or 'missing value' for 1000 in Snow Leopard or later and 1024 otherwise). The 'decPlaces' parameter specifies to how many decimal places the result is to be rounded (but not padded).
on convertByteSize(byteSize, KBSize, decPlaces)
   if (KBSize is missing value) then set KBSize to 1000 + 24 * (((system attribute "sysv") < 4192) as integer)
   
   if (byteSize is 1) then
       set conversion to "1 byte" as Unicode text
   else if (byteSize < KBSize) then
       set conversion to (byteSize as Unicode text) & " bytes"
   else
       set conversion to "Oooh lots!" -- Default in case yottabytes isn't enough!
       set suffixes to {" K", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"}
       set dpShift to ((10 ^ 0.5) ^ 2) * (10 ^ (decPlaces - 1)) -- (10 ^ decPlaces) convolutedly to try to shake out any floating-point errors.
       repeat with p from 1 to (count suffixes)
           if (byteSize < (KBSize ^ (p + 1))) then
               tell ((byteSize / (KBSize ^ p)) * dpShift) to set conversion to (((it div 0.5 - it div 1) / dpShift) as Unicode text) & item p of suffixes
               exit repeat
           end if
       end repeat
   end if
   
   return conversion
end convertByteSize


convertByteSize(199555, 1024, 1) --> "194.9 K"
convertByteSize(199555, 1000, 2) --> "199.56 K"
convertByteSize(199555, missing value, 2) --> "194.88 K" or "199.56 K", depending on the current system.

Last edited by Nigel Garvey (2011-09-14 01:49:00 pm)


NG

Offline

 

#2 2011-09-14 02:59:36 pm

Adam Bell
Administrator
From:: Nova Scotia, Canada
Registered: 2005-10-04
Posts: 4666

Re: Bytes to kilobytes, megabytes, etc., with suffix

Does a nice job even for numbers like 76621225984 --> 71.36 GB or 2000204886016 --> 1.82 TB (with a KB set to 1024)


Mac mini running 10.14.6, 2011 27" iMac as display.

Offline

 

#3 2011-09-14 03:24:24 pm

DJ Bazzie Wazzie
Member
From:: the Netherlands
Registered: 2004-10-20
Posts: 2809
Website

Re: Bytes to kilobytes, megabytes, etc., with suffix

Great work Nigel!

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)