0

Possible Duplicate:
How to convert byte size into human readable format in java?

Given an integer, I'd like to print it in a human-readable way using kilo, mega, giga etc. multipliers. How do I pick the "best" multiplier?

Here are some examples

        1 print as 1
    12345 print as 12.3k
987654321 print as 988M

Ideally the number of digits printed should be configurable, e.g. in the last example, 3 digits would lead to 988M, 2 digits would lead to 1.0G, 1 digit would lead to 1G, and 4 digits would lead to 987.7M.

Example: Apple uses an algorithm of this kind, I think, when OSX tells me how many more bytes have to be copied.

This will be for Java, but I'm more interested in the algorithm than the language.

Community
  • 1
  • 1
Johannes Ernst
  • 3,072
  • 3
  • 42
  • 56
  • I think you've got some solid unit tests in your question, all you need to do now is write the algorithm and test each case until they all validate. Only you know exactly what you want. Start with a couple until they validate, then move on doing one more each time. – TheZ Oct 17 '12 at 23:09
  • I was hoping I didn't have to write it myself... I hardly think I'm the first one who ever wanted to have that algorithm... – Johannes Ernst Oct 17 '12 at 23:11
  • Take a look at [this answer](http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc). I think it does what you're after. – Tweeds Oct 17 '12 at 23:13
  • The answer is here http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java/3758880#3758880 – Zied Hamdi Mar 10 '14 at 10:58

1 Answers1

2

As a starting point, you could use the Math.log() function to get the "magnitude" of your value, and then use some form of associative container for the suffix (k, M, G, etc).

var magnitude = Math.log(value) / Math.log(10);

Hope this helps somehow

Luc Morin
  • 5,302
  • 20
  • 39
  • Just noticed this answer using the log method: http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java/3758880#3758880 – Luc Morin Oct 17 '12 at 23:16
  • That's a good idea indeed. Much like the dB (decibel) scale used to compare values with varying orders of magnitude. – Paulo Carvalho Aug 09 '17 at 11:11