在JavaScript中实现数字格式化可以通过以下代码示例:
function number_format(number, decimals, dec_point, thousands_sep) {
number = parseFloat(number);
if(isNaN(number) || !isFinite(number)) {
return number;
}
decimals = decimals || 0;
dec_point = dec_point || '.';
thousands_sep = thousands_sep || ',';
var roundedNumber = Math.round(Math.abs(number) * Math.pow(10, decimals)) / Math.pow(10, decimals);
var roundedString = roundedNumber.toString();
var decIndex = roundedString.indexOf('.');
var integerPart = decIndex > -1 ? roundedString.slice(0, decIndex) : roundedString;
var decimalPart = decIndex > -1 ? roundedString.slice(decIndex) : '';
var formattedNumber = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1" + thousands_sep);
if(decimals > 0) {
formattedNumber += dec_point + (decimalPart + '000000').slice(2, decimals + 2);
}
return formattedNumber;
}
// 示例
var number = 1234567.8901;
var formattedNumber = number_format(number, 2, '.', ',');
console.log(formattedNumber); // 输出: 1,234,567.89
在上面的代码中,number_format
函数实现了数字的格式化功能,可以指定小数点位数、小数点符号和千位分隔符。您可以根据需要调整参数和格式化规则。