代码改变世界

千位格式化正则

2009-09-14 23:27  BlueDream  阅读(519)  评论(0编辑  收藏  举报
千位格式化:就是所谓的金钱格式,数字逢三加一个逗号.比如1000-->1,000   1233333-->1,233,333等等.相信大家都能看懂.
由于javascript支持正向预搜查,那么实现起来就不难了.
这里给出一个可以自己定制规则的思想.比如下面的代码不对以字母,下划线和.开头的数字进行格式化.
<script type="text/javascript">
<!--
String.prototype.commafy = function(){
    return this.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2){
        return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g,"$&,");
    });
}

Number.prototype.commafy = function(){
    return String(this).commafy();
}

alert((1000).commafy()) // 1,000
var data = '1\n' +
    '10\n' +
    '100\n' +
    '1000\n' +
    '10000\n' +
    '100000\n' +
    '1000000\n' +
    '12345678901234567890\n' +
    '1000.99\n' +
    '1000.9999\n' +
    '.9999\n' +
    '-1000\n' +
    '$1000\n' +
    '"1000"\n' +
    '1000MHz\n' +
    'Z1000';
alert(data.commafy());
/* Output:
1
10
100
1,000
10,000
100,000
1,000,000
12,345,678,901,234,567,890
1,000.99
1,000.9999
.9999
-1,000
$1,000
"1,000"
1,000MHz
Z1000
*/

//-->
</script>