C# Human Readable File Size Optimized Function

This is a highly optimized function to get the file size abbreviation in bytes for an arbitrary, 64-bit file size. It returns the file size to three decimals followed by the abbreviation, like KB, MB, GB, etc. Use this function to display a human-readable, user-friendly file size to your users.

Below is the human readable file size function source code. You can get a Visual Basic (VB.Net) version by using the C# to VB.Net Convertor Tool.

C# Human-Readable File Size Function

The code below is dedicated to the public domain under the Unlicense or CC0, whichever is most appropriate for your use. Attribution is not necessary, but a vote on the post at stackoverflow would be appreciated.

This is not a function likely to be called very frequently in any individual program, so it may not be important to your project to shave some microseconds off this function call. However, I'm posting this here because if you add up the number of times it is called all over the world, there is a great potential savings of CPU-cycles if everyone were to use an optimized version.

This version is about two times faster and more efficient overall than David Thibault's version, the top-rated post on StackOverflow as of this writing. (If you take out the ToString, the most expensive function, the math portion is over 10 times faster.) Here are the key optimizations and features versus other versions posted there.