I’d like to get the first three digits from large floats or integers and on some insert a decimal. For example:
KB
----------
32589 >> 325
43266 >> 432
MB
----------
1234599 >> 1.23
3422847 >> 3.42
For the particular number, I will have the “KB” and “MB” strings. This will let me know if the decimal is required, as in “MB” examples. I looked at NSNumberFormatter but wasn’t sure what on there would help. Any suggestions?
Actually, decided to chime in with my own answer. This is my routine for generating strings for outputting human sizes from byte counts:
It works out the correct size by seeing what order of binary magnitude it is, using 1024 as the base (1024 bytes = 1KB, 1024KB = 1MB, etc.). While doing this, it shrinks the input value (using floating-point arithmetic) such that once it’s below 1024, it has both a human-readable value and a magnitude specifier. It then generates a string containing the formatted value (no decimal places for bytes, 2 decimal places for any larger magnitude), and inspects the magnitude constant to determine what suffix to attach.