Formatting File Sizes with NSByteCountFormatter

July 14, 2013

This is one of the little things that are easy to overlook (or quickly forget) when a new SDK is released. NSByteCountFormatter was introduced in iOS 6, but I somehow just found out about it yesterday. As the name implies, this class converts a number of bytes into a human-readable file size (e.g. "1.2 MB").

While it isn't particularly hard to do this manually, NSByteCountFormatter takes care of some details that are easy to overlook, e.g. adaptively adjusting the number of fraction digits depending on the unit:

The "adaptive" algorithm is platform specific and uses a different number of fraction digits based on the magnitude (on OS X v10.8: 0 fraction digits for bytes and KB; 1 fraction digits for MB; 2 for GB and above). Otherwise the result always tries to show at least three significant digits, introducing fraction digits as necessary.

Similar to NSDateFormatter, using this should also ensure that the display of file sizes is consistent with the rest of the system.