public static function seperateFormat(num:String, precision:int):String { if (!isNaN(Number(num))&&precision>=-1) { var input:BigDecimal = new BigDecimal(num); var output:String; if (precision != -1) { output = input.divideScaleRound(new BigDecimal(1), precision, MathContext.ROUND_HALF_EVEN).toString(); } else { output = input.divide(new BigDecimal(1)).toString(); } var temp:Array = output.split("."); var interger:String = temp[0]; var decimal:String = temp[1]; var sign:String = ""; if (interger.substr(0, 1) == "-") { sign = "-"; interger = interger.substring(1, interger.length); } var result:String = ""; var maxLoop:int = Math.ceil(interger.length / 3); for (var i:int = maxLoop; i >= 1; i--) { var tempInterger:String; if (i == maxLoop) { tempInterger = Number(interger.substring(0, interger.length - 3 * (i - 1))).toString(); } else { tempInterger = interger.substring(interger.length - 3 * i, interger.length - 3 * (i - 1)); } result = result + "," + tempInterger; } if (result.substring(0, 1) == ",") { result = result.substring(1, result.length); } result = sign+result; if (decimal == null) { return result.substring(0, result.length); } return result.substring(0, result.length) + '.' + decimal; } return num; }
Flex当需要对一个很长的number进行NumberFormatter时 , 我发现flex的Number不像BigDecimal一样具有很大的精度,当超过15位时,用NumberFormatter后就会使原number丢失精度,这里使用了BigDecimal和MathContext两个外部类。可从
http://code.google.com/p/bigdecimal/ 这里获得 。经过多方修整,这个版本是测试以来最好的版本了。
例子:
seperateFormat("123123123123.773" , 3); result: 123,123,123,123.773