javascript - Javascript - 添加逗号和小数

代码在没有错误的情况下运行,当我console.log等式时,我得到正确的输出。但是,函数thousands_seperators在网页上显示不正确。

代码如下:


if (isFinite(monthly)) {


 // monthlyPayment.value = monthly.toFixed(2)


 // totalPayment.value = (monthly * calculatedPayments).toFixed(2);


 // totalInterest.value = ((monthly * calculatedPayments) - principal).toFixed(2);



 // UPDATE TO ADD DECIMAL POINTS


 function thousands_separators(num) {


 var num_parts = num.toString().split(".");


 num_parts[0] = num_parts[0].replace(/B(?=(d{3})+(?!d))/g,",");


 return num_parts.join(".");


 }



 console.log(thousands_separators(monthlyPayment.value = monthly.toFixed(2)));


 console.log(thousands_separators(totalPayment.value = (monthly * calculatedPayments).toFixed(2)));


 console.log(thousands_separators(totalInterest.value = ((monthly * calculatedPayments) - principal).toFixed(2)));



 // SHOW RESULTS


 document.getElementById("results").style.display ="block";


 // HIDE LOADER


 document.getElementById("loading").style.display ="none";



} else {


 showError("Please check that all fields are filled out")


}



时间:

分解这段代码:

这就是它的工作原理


var result = ((monthly * calculatedPayments) - principal).toFixed(2)


totalInterest.value = result


console.log(thousands_separators(result));



使用变量,执行多个步骤。


var result = ((monthly * calculatedPayments) - principal).toFixed(2)


var formatted = thousands_separators(result)


totalInterest.value = formatted


console.log(formatted);



...