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.

-- 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.

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

Great work Nigel!