Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

how to connect the comma function to my input calculator?

hello. i wrote a calculator function with the solution in the dom. i looked for a function to add commas for the numbers but dont now how to connect the two. this is the 2 functions: function calculateResults() { // הדום של החישוב const amount = document.getElementById("amount"); const interest = document.getElementById("interest"); const years = document.getElementById("years"); // const hodash = document.getElementById("hodesh"); const monthlyPayment = document.getElementById("monthly-payment"); const totalPayment = document.getElementById("total-payment"); const totalInterest = document.getElementById("total-interest"); // פעולת החישוב const principal = parseFloat(amount.value); const calculatedInterest = parseFloat(interest.value) / 100; const calculatedPayments = parseFloat(years.value); // const hodshi = parseFloat(hodash.value) * 12; // תשלום חודשי מחושב FV = principal * Math.pow(1 + calculatedInterest, calculatedPayments);

if (isFinite(FV)) {
  totalInterest.value = FV.toFixed(2);
  totalPayment.value = (FV - principal).toFixed(2);
  monthlyPayment.value = principal.toFixed(2);
};

} // פסיקים function format(num, fix) { var p = num.toFixed(fix).split("."); return p[0].split("").reduceRight(function(acc, num, i, orig) { if ("-" === num && 0 === i) { return num + acc; } var pos = orig.length - i - 1 return num + (pos && !(pos % 3) ? "," : "") + acc; }, "") + (p[1] ? "." + p[1] : ""); }

the first is the calculator and the second the commas. how i connect them? in a way that the calculator output will be with commas?

2 Answers

Steven Parker
Steven Parker
231,141 Points

Instead of using "toFixed", you can pass your values to your formatting function:

    totalInterest.value = format(FV, 2);

But you don't need to "reinvent the wheel" unless you really want to. Just, use "toLocalizeString" instead of "toFixed":

    totalInterest.value = FV.toLocaleString("en-US", {maximumFractionDigits: 2});

thank you and how to re write the other 2?

Steven Parker
Steven Parker
231,141 Points

You can substitute the code shown in my 2nd example every place you have ".toFixed(2)".