How to convert byte size into human-readable format in Java? Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb".
I am kind of sick of writing this utility method for each project. Are there any static methods in Apache Commons for this?
We can completely avoid using the slow
Math.pow()
andMath.log()
methods without sacrificing simplicity since the factor between the units (e.g. B, KB, MB etc.) is 1024 which is 2^10. TheLong
class has a handynumberOfLeadingZeros()
method which we can use to tell which unit the size value falls in.Key point: Size units have a distance of 10 bits (1024=2^10) meaning the position of the highest 1 bit - or in other words the number of leading zeros - differ by 10 (Bytes=KB*1024, KB=MB*1024 etc.).
Correlation between number of leading zeros and size unit:
The final code:
I know it's too late to update this post! but I had some fun with this:
Create an interface:
Create StorageUnits class:
Call it:
Output:
Here's the C# .net equivalent for Java correct consensus answer above. (there's another below which have shorter codes)
Technically speaking, if we stick to SI units, this routine works for any regular use of numbers. There are many other good answers from experts. Suppose you are doing databinding of numbers on gridviews, its worth to check out performance optimized routines from them.
PS: Posted because this question/answer came up on top on google search while I am doing C# project.
Have you tried JSR 363? Its unit extension modules like Unicode CLDR (in GitHub: uom-systems) do all that for you.
You can use
MetricPrefix
included in every implementation orBinaryPrefix
(comparable to some of the examples above) and if you e.g. live and work in India or a nearby country,IndianPrefix
(also in the common module of uom-systems) allows you to use and format "Crore Bytes" or "Lakh Bytes", too.You can use StringUtils’s
TraditionalBinarPrefix
:There is now one library available that contains unit formatting. I added it to the triava library, as the only other existing library seems to be one for Android.
It can format numbers with arbitrary precision, in 3 different systems (SI, IEC, JEDEC) and various output options. Here are some code examples from the triava unit tests:
Printing exact kilo, mega values (here with W = Watt):
You can pass a DecimalFormat to customize the output:
For arbitrary operations on kilo or mega values, you can split them into components: