Michael Hasenstein wrote: > That looks very acceptable to me and a lot of people. Of course, do what > you want, the only reason I post is because when *I* found this thread > looking for such a functionality I copied your code, and only then > realized there's a function already. I respond to let others know right > away who find this through Google.
I think it's excellent that you recorded for the record the simplest case for others to follow. To be clear, here's the output I want (and have): [ 1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890 ].each{ |bytes| puts nice_bytes( bytes ) } #=> 1b #=> 12b #=> 123b #=> 1.21kB #=> 12.1kB #=> 121kB #=> 1.18MB #=> 11.8MB #=> 118MB #=> 1.15GB With the exception of bytes, I get two decimal places when there are less than 10 of the amount, one decimal place with less than a hundred, and no decimal places for hundreds. Windows does this, and I actually like it. Although unrelated to real significant figures, it's similar: there are ~always 3 digits displayed. As the number grows in magnitude, I am less interested in the details of the exact decimals. When working with a large number of files all in the same rough range, this lets me automatically visually display them in a way that allows them to be compared and distinguished, without too much detail. *shrug* Not a big deal. As you say, most people will find the rails method suits their needs. BTW, here's updated 1.9 compatible code for the function: K = 2.0**10 M = 2.0**20 G = 2.0**30 T = 2.0**40 def nice_bytes( bytes, max_digits=3 ) value, suffix, precision = case bytes when 0...K [ bytes, 'b', 0 ] else value, suffix = case bytes when K...M then [ bytes / K, 'kB' ] when M...G then [ bytes / M, 'MB' ] when G...T then [ bytes / G, 'GB' ] else [ bytes / T, 'TB' ] end used_digits = case value when 0...10 then 1 when 10...100 then 2 when 100...1000 then 3 end leftover_digits = max_digits - used_digits [ value, suffix, leftover_digits > 0 ? leftover_digits : 0 ] end "%.#{precision}f#{suffix}" % value end -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk@googlegroups.com To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---