js数字格式化

JS数字格式化函数
关键字: number format
前几天在blog里贴了个JS货币格式化的函数,今天在Matt Snider的网站上淘到了另一个不错的东西,不过和之前说的那个函数有点差别,这个函数是用来格式化数字类型的,很好,很实用。

ps:Matt Snider的网站正如其title一样——Matt Snider JavaScript Resource,内容相当多,个个都比较实用,我喜欢。

/**
* Formats the number according to the ‘format’ string; adherses to the american number standard where a comma is inserted after every 3 digits.
* note: there should be only 1 contiguous number in the format, where a number consists of digits, period, and commas
* any other characters can be wrapped around this number, including ‘$’, ‘%’, or text
* examples (123456.789):
* ‘0′ - (123456) show only digits, no precision
* ‘0.00′ - (123456.78) show only digits, 2 precision
* ‘0.0000′ - (123456.7890) show only digits, 4 precision
* ‘0,000′ - (123,456) show comma and digits, no precision
* ‘0,000.00′ - (123,456.78) show comma and digits, 2 precision
* ‘0,0.00′ - (123,456.78) shortcut method, show comma and digits, 2 precision
*
* @method format
* @param format {string} the way you would like to format this text
* @return {string} the formatted number
* @public
*/

Number.prototype.format = function(format) {
if (! isType(format, ’string’)) {return ”;} // sanity check

var hasComma = -1 < format.indexOf(’,'),
psplit = format.stripNonNumeric().split(’.'),
that = this;

// compute precision
if (1 < psplit.length) {
// fix number precision
that = that.toFixed(psplit[1].length);
}
// error: too many periods
else if (2 < psplit.length) {
throw(’NumberFormatException: invalid format, formats should have no more than 1 period: ‘ + format);
}
// remove precision
else {
that = that.toFixed(0);
}

// get the string now that precision is correct
var fnum = that.toString();

// format has comma, then compute commas
if (hasComma) {
// remove precision for computation
psplit = fnum.split(’.');

var cnum = psplit[0],
parr = [],
j = cnum.length,
m = Math.floor(j / 3),
n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop

// break the number into chunks of 3 digits; first chunk may be less than 3
for (var i = 0; i < j; i += n) {
if (i != 0) {n = 3;}
parr[parr.length] = cnum.substr(i, n);
m -= 1;
}

// put chunks back together, separated by comma
fnum = parr.join(’,');

// add the precision back in
if (psplit[1]) {fnum += ‘.’ + psplit[1];}
}

// replace the number portion of the format with fnum
return format.replace(/[d,?.?]+/, fnum);
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值