number_to_human_size in Flex

Here's a code sample to turn any number into a human-readable size in bytes, in Flex.

Enjoy!

 
 package com.yourapp.lib.utils 
 { 
 import com.yourapp.lib.utils.MathUtils; 
 
 public class NumberUtils 
 { 
 public static const GIGABYTE:Number = 1073741824; 
 
 private static const _formats:Array = [ 
 "Bytes", 
 "KB", 
 "MB", 
 "GB", 
 "TB" 
 ]; 
 
 private static const _sizes:Array 	= [ 
 1, 
 1024, 
 1048576, 
 1073741824, 
 1099511627776 
 ]; 
 
 public static function humanSize(value:Number, digits:int=1):String { 
 if (value == 0) { 
 return "0 Bytes"; 
 } 
 
 for (var i:Number = _sizes.length; i >= 0; i--) { 
 if (value >= _sizes[i]) { 
 break; 
 } 
 } 
 
 return MathUtils.round(value / _sizes[i], digits) + " " + _formats[i]; 
 } 
 } 
 
 } 
 
 package com.yourapp.lib.utils 
 { 
 public class MathUtils 
 { 
 public static function round(value:Number, decimals:int = 0):Number { 
 var rounder:Number = Math.pow(10, decimals); 
 return Math.round(value * rounder) / rounder; 
 } 
 
 } 
 
 } 
 

Customer hyperservice

I think it's fitting to dedicate my first post on this posterous blog to posterous itself.

Only a few hours ago, I was toying with the idea of starting this geek blog on posterous, but I couldn't figure out how to post code samples. That's a pretty essential feature from my point of view, and I wrote up a short post on Hacker News to find out if maybe I just didn't know how I was supposed to do it.

Within about half an hour, one of the posterous cofounders responded and picked up the suggestion. The feature is now being built as we speak. Someone also mentioned putting <code> tags within the posterous html editor as a workaround. So there you go. I can now start my geek blog on posterous.

Awesome.