-3

I have created a calculator that shows the output of savings with a specific calculation. I just need the result to be formatted with commas and to be currency so it does not show every number after the decimal. For example if the outcome was:

$2500.566695969 I would only want it to show: $2,500.56

I hope that makes sense, I tried a couple of things to get the comma in the right place but nothing worked. I am a bit newer to jQuery and this is my first attempt at a calculator like this. Any help is really appreciated. Below is my code.

function calculate() {
    var savingsVal = (jQuery('#savingsVal').val());
    var totalSavings = 0;
    var regType = (jQuery('#reg-type').val());

    if (filterValues(savingsVal)) {
        totalSavings = savingsVal * 0.15 * 3 - regType * 3;
    }

    jQuery('#totalSavings').val('$' + totalSavings);
}


function filterValues(eVal) {
    return true;
}

jQuery('.results-area').hide();

jQuery('#calculator').submit(function(e) {
    e.preventDefault();
    calculate();
    jQuery('.results-area').show("slow");
    jQuery(this).text( jQuery(this).submit().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
});
Cœur
  • 37,241
  • 25
  • 195
  • 267
AaronS
  • 131
  • 13
  • 2
    Possible duplicate of [jQuery: Currency Format Number](https://stackoverflow.com/questions/5807155/jquery-currency-format-number) – jhpratt Dec 09 '17 at 00:02
  • Are you looking for an algorithm that will format money? Or would you be satisfied using a library that already does this? I would recommend the latter. – wpcarro Dec 09 '17 at 00:03
  • I'd highly recommend you to use a good library like accounting.js. http://openexchangerates.github.io/accounting.js/ . It has a method called `formatMoney` that will do everything you want to. – TeaCoder Dec 09 '17 at 00:07
  • Related: https://stackoverflow.com/questions/16148034/regex-for-number-with-decimals-and-thousand-separator – ericw31415 Dec 09 '17 at 00:08
  • I just want it to output in a currency format. Whatever works easiest. – AaronS Dec 09 '17 at 00:14

2 Answers2

1

This looks a little obnoxious but below is a working function.

It accepts a string containing a number. It doesn't matter if the string contains a '$' or not.

It returns a string formatted with commas without the preceding '$', but this is easily added of course.

function toCurrency(str) {
    let ret = parseFloat(str[0] === '$' ? str.substr(1) : str).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if (!isNaN(ret))
 return str;
    return ret;
}

let elem = document.getElementById('money');
elem.innerHTML = '$' + toCurrency(elem.innerHTML);
<p id="money">$2500.566695969</p>
Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109
0

You can try /(\d)(?=(\d{3})+(?!\d))/g, "$1," instead of your current Regex in the replace function.

Philip Lee
  • 93
  • 3
  • 7