在 Javascript 中为数字添加逗号
Posted
技术标签:
【中文标题】在 Javascript 中为数字添加逗号【英文标题】:Add commas to numbers in Javascript 【发布时间】:2018-04-15 18:28:23 【问题描述】:我正在为我的班级编写一个程序,我们还没有真正了解如何用逗号格式化数字,我做了一些研究并尝试使用 toLocalestring(),但无法让它工作。我不确定我是否没有把它放在正确的位置,或者是否有另一种方法可以将逗号放在我想要的位置。我将发布我的代码,看看是否有人知道我需要做什么。我只需要逗号显示在余额和已付利息列中。另外,此时我必须根据课程要求使用 console.log() 。
function displayWelcome()
console.log("Welcome!");
console.log("This program will determine the time to pay off a credit card and the interest paid based on the current balance, the interest rate, and the monthly payments made.");
function calculateminimumPaymentment(balance, minimumPaymentRate)
return Math.max(20, balance * minimumPaymentRate);
function displayPayments(balance, interest, minimumPayment)
var pad = 17;
console.log("Balance on your credit card: $" + balance.toFixed(2));
console.log("Interest Rate: " + (interest * 100) + "%");
console.log("Assuming a minimum payment of 2% of the balance ($20 min)");
console.log("Your minimum payment would be: $" + minimumPayment);
console.log();
console.log('Year'.padStart(pad), 'Balance'.padStart(pad - 10), 'Payment Number'.padStart(pad - 1), 'Interest Paid'.padStart(pad - 4), 'Minimum Payment'.padStart(pad - 3));
var acum = 0;
var yearcount = 0;
var paynum = 0;
var interestPaid = 1;
var year = 0;
while (balance > 0)
paynum++;
interestPaid = balance * (interest / 12);
balance = Math.max(0, balance - (minimumPayment - balance * interest / 12));
minimumPayment = Math.max(20, balance * minimumPaymentRate);
acum = (parseFloat(acum) + parseFloat(interestPaid)).toFixed(2);
if (yearcount % 12 === 0)
year++;
console.log(
('' + year).padStart(pad),
'$' + parseFloat(balance).toFixed(2).padStart(pad - 9),
('' + paynum).padStart(pad - 3),
'$' + parseFloat(interestPaid).toFixed(2).padStart(pad - 5),
'$' + parseFloat(minimumPayment).toFixed(2).padStart(pad - 3)
);
else
console.log(
''.padStart(pad),
'$' + parseFloat(balance).toFixed(2).padStart(pad - 9),
('' + paynum).padStart(pad - 3),
'$' + parseFloat(interestPaid).toFixed(2).padStart(pad - 5),
'$' + parseFloat(minimumPayment).toFixed(2).padStart(pad - 3)
);
yearcount++;
var balance = 1500;
var minimumPaymentRate = 0.02;
var interest = 0.18;
displayWelcome();
var minimumPayment = calculateminimumPaymentment(balance, minimumPaymentRate);
displayPayments(balance, interest, minimumPayment);
【问题讨论】:
在询问之前尝试搜索类似的问题。您的问题有很多问题和答案。见***.com/questions/149055/… How can I format numbers as dollars currency string in javascript?的可能重复 愿这 (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) 对您有所帮助 【参考方案1】:您必须自己格式化数字。先将其转为字符串,然后用正则表达式将点替换为逗号:
var a = 1234.5678;
var b = a.toFixed(2);
var c = b.replace(/\./, ',');
console.log(a, b, c);
【讨论】:
以上是关于在 Javascript 中为数字添加逗号的主要内容,如果未能解决你的问题,请参考以下文章