/* *js格式化數字代碼 * *value: 要格式化的數字值 *scale: 最多保留幾位小數 *zeroed: 是否保留尾0 *percented: 是否轉稱百分比形式 * */ function formatNumber(value, scale, zeroed, percented){ i ...
/*
*js格式化數字代碼
*
*value: 要格式化的數字值
*scale: 最多保留幾位小數
*zeroed: 是否保留尾0
*percented: 是否轉稱百分比形式
*
*/
function formatNumber(value, scale, zeroed, percented){
if (value == null)
return percented ? '0%' : 0;
var mr = (''+value).match(/^\d+\.?\d*$/);
if (!mr)
return percented ? '0%' : 0;
mr = (percented ? (value = Number(mr[0]) * 100)+'' : mr[0]).split('.');console.info(mr);
if (mr.length == 1)
return (zeroed ? (mr[0] + ((function(){var r = '.';for (var i = 0; i < scale; i++) {
r += '0';
}return r;}()))) : mr[0]) + (percented ? '%' : '');
var mr_l = mr[0], mr_r = mr[1];
if (mr_r.length == scale)
return (zeroed ? (mr_l + '.' + mr_r) : (value + '').replace(/\.*0+$/, '')) + (percented ? '%' : '');
else if (mr_r.length < scale)
return (zeroed ? value + ((function(){var r = ''; for (var i = 0; i < scale - mr_r.length; i++) {
r += '0';
}return r;})()) : (value + '').replace(/\.*0+$/, '')) + (percented ? '%' : '');
else {
var _s = mr_r.substr(0, scale + 1);
_s = _s.charAt(scale) > 4 ? (Number(_s.substring(0, scale)) + 1) + '' : _s.substring(0, scale);
if (_s.length == (scale + 1)){
mr_l = (Number(mr_l) + Number(_s.charAt(0))) + '';
_s = _s.substring(1);
}
return (zeroed ? (mr_l + '.' + _s) : (mr_l + (_s.match(/^0*$/) ? '' : ('.' + _s.replace(/0+$/, '')))))
+ (percented ? '%' : '');
}
};