-
忽然笑
对于整数:var x=12345678;x=x.toString();var lastThree = x.substring(x.length-3);var otherNumbers = x.substring(0,x.length-3);if(otherNumbers != '') lastThree = ',' + lastThree;var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;alert(res);对于浮点数:var x=12345652457.557;x=x.toString();var afterPoint = '';if(x.indexOf('.') > 0) afterPoint = x.substring(x.indexOf('.'),x.length);x = Math.floor(x);x=x.toString();var lastThree = x.substring(x.length-3);var otherNumbers = x.substring(0,x.length-3);if(otherNumbers != '') lastThree = ',' + lastThree;var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;alert(res);
-
MMMHUHU
我迟到了,但我想这会有所帮助的:)您可以使用Number.prototype.toLocaleString()句法numObj.toLocaleString([locales [, options]])var number = 123456.789;// India uses thousands/lakh/crore separatorsdocument.getElementById('result').innerHTML = number.toLocaleString('en-IN');// → 1,23,456.789document.getElementById('result1').innerHTML = number.toLocaleString('en-IN', { maximumFractionDigits: 2, style: 'currency', currency: 'INR'});// → Rs.123,456.79<div id="result"></div><div id="result1"></div>
-
人到中年有点甜
对于整数,不需要其他操作。这将匹配末尾的每个数字,其后具有1个或多个双位数字模式,并将其替换为自身+“,”:"125465778".replace(/(\d)(?=(\d\d)+$)/g, "$1,");-> "1,25,46,57,78"但是,由于我们希望末尾有3个,因此让我们通过在输入的匹配末尾之前添加额外的“ \ d”来明确声明这一点:"125465778".replace(/(\d)(?=(\d\d)+\d$)/g, "$1,");-> "12,54,65,778"