Javascript 无固定小数
嗨,我需要格式化我的数字以防止小数点过多 我需要像Javascript 无固定小数,javascript,Javascript,嗨,我需要格式化我的数字以防止小数点过多 我需要像 1.123 its good 1.12345678 its good too 1.12345678900001 format to 1.12345678 with maximum 8 decimal 现在我只使用一个函数来添加逗号,而不使用十进制 function commas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length
1.123 its good
1.12345678 its good too
1.12345678900001 format to 1.12345678 with maximum 8 decimal
现在我只使用一个函数来添加逗号,而不使用十进制
function commas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
谢谢我建议您使用这个jQuery插件。您可以使用此插件格式化文本节点,根据需要输入节点的值 如果你不想使用这个插件,你也可以引用格式化方法 您可以在此插件中引用
格式
方法
正则表达式的主要格式为:
integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, options.thousands);
也许这就是诀窍:
function commas(nStr,maxDecimals){
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
x1 = x1.replace('.',','); //replace . into ,
x2 = x2.substr(0, maxDecimals) ; //select the max amount of decimals
return x1 + x2;
}
只需将
x[1]
替换为x[1].substr(0,8)
?这实际上似乎是两个问题——第一个问题是“如何将我的数字限制为8 d.p.”,第二个问题是“如何用逗号分隔数字?”“除非还包含框架/库的标记,否则需要纯JavaScript的答案。”引用正则表达式的格式。可以使用此正则表达式设置整数部分和小数部分的格式。然后把它们加在一起。