commaFormat
public static inline function commaFormat( num:Float ): String var str:String = Std.string(num); var str_ar:Array<String> = new Array<String>(); var pos:Int = 1; var i:Int; var out:String = ""; if (str.indexOf(".") == -1 ){ str_ar = str.split(""); }else{ out = str.substr(str.indexOf(".")); str_ar = str.substr(0, str.indexOf(".")).split(""); } str_ar.reverse(); for (i in 0...str_ar.length){ out = str_ar[i]+out; if (pos++ == 3) { pos = 1; out = ((Math.isNaN(Std.parseFloat(str_ar[0])) && i > 1) || (!Math.isNaN(Std.parseFloat(str_ar[0])) && i >= 1) && i < str_ar.length-1) ? ","+out : out; } } return out; }
trace(commaFormat(123));
// output: 123
trace(commaFormat(123456));
// output: 123,456
trace(commaFormat(1234567890.12345));
// output: 1,234,567,890.12345
can be written better, however this should be fast enough in most cases.
var i:Int; var s:StopWatch = new StopWatch(); for(i in 0...10000){ Utils.commaFormat(123123123123123123123); } s.stop(); trace(s);
0.767 ms
version #6838, modified 2009-08-23 14:49:35 by theRemix