将数字格式化为字符串-带小数和千位分隔符
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数字格式化为字符串-带小数和千位分隔符相关的知识,希望对你有一定的参考价值。
Format a number so it is more humanly readable. It allows for setting the number of decimal places (inc. adding 0000s to the end) and separating thousands with a comma.Example usage:
trace(numberFormat(1234.695, 2, true, false));
// Output: 1,234.70
trace(numberFormat(16000000, 0, false, false));
// Output: 16,000,000
function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = true):String { Â Â Â Â var i:int = 0; var inc:Number = Math.pow(10, maxDecimals); var str:String = String(Math.round(inc * Number(number))/inc); Â Â Â Â var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf("."); Â Â Â Â var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1); Â Â Â Â if (forceDecimals) { for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0"; } Â Â Â Â while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret; Â Â Â Â return str.substr(0, sep - i) + ret; }
以上是关于将数字格式化为字符串-带小数和千位分隔符的主要内容,如果未能解决你的问题,请参考以下文章