金额显示,每3位加逗号
2016-01-29 15:28 xiashengwang 阅读(1858) 评论(0) 编辑 收藏 举报function format_number(n) { n = n + ''; var re = /^-?[0-9]+.?[0-9]*$/; if (!re.test(n)) { return n; } var pos = n.indexOf("."); var part1; var part2; if (pos > -1) { part1 = n.substr(0, pos); part2 = n.substr(pos + 1); } else { part1 = n; } var sign = ''; if (part1.indexOf('-') > -1) { sign = part1.slice(0, 1); part1 = part1.slice(1); } var len = part1.length; if (len > 3) { var r = len % 3; part1 = r > 0 ? part1.slice(0, r) + "," + part1.slice(r, len).match(/\d{3}/g).join(",") : part1.slice(r, len).match(/\d{3}/g).join(","); } if (part2) { return sign + part1 + '.' + part2; } else { return sign + part1; } };
效果如下;
1234.01 ⇒1,234.01
-1234.01 ⇒-1,234.01