在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
函數實現了數字的格式化功能,可以指定小數點位數、小數點符號和千位分隔符。您可以根據需要調整參數和格式化規則。