Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper JS currency format with commas and decimals

I have looked through countless threads here and elsewhere for over 2 days and I cannot get this to work properly.

I have a calculator working exactly the way I need it to, however, I can't seem to get one last thing complete. Comma separator by thousands with decimal.

I have the decimal places, but can't add commas. When I do add commas, I can get one or two fields to work before the calculation breaks or the value is displayed as NaN.

Here is the working page: http://codepen.io/anon/pen/Fauzy

It currently uses this:

function FormatAsMoney(mnt) {
mnt -= 0;
mnt = (Math.round(mnt*100))/100;
return (mnt == Math.floor(mnt)) ? mnt + '.00'
: ( (mnt*10 == Math.floor(mnt*10)) ?
mnt + '0' : mnt);
}

If I try to use this :

function FormatAsMoney(x)

        {


            var money_value;

            mnt = x.value;

            mnt = mnt.replace(/\,/g,'');

            mnt -= 0;

            mnt = (Math.round(mnt*100))/100;

            money_value = (mnt == Math.floor(mnt)) ? mnt + '.00' : ( (mnt*10 == Math.floor(mnt*10)) ? mnt + '0' : mnt);

            if (isNaN(money_value))
            { 
                money_value ="0.00";

            }else{
        money_value = CommaFormatted(money_value);      
        x.value = money_value.replace(".00", "");
    }

}

It doesn't work at all.

I did another test using :

function FormatAsMoney(str) {
  return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
    return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
  });
}

In which I get the comma formatting on the first field, but lose decimals and it does not continue any other calculation.

As another example I created another function to add the commas like :

function addCommas(nStr){
    nStr += '';
    c = nStr.split(','); // Split the result on commas
    nStr = c.join('');  // Make it back to a string without the commas
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

I then use it like:

document.Rate.RATE.value=addCommas(FormatAsMoney(dasum));

Which seems to be the best outcome I have had yet, however on line (163) where, for example, function dosum() depends on many if statements, It breaks the again. I can't seem to get it to work for all applicaable fields where the value would be in thousands.

I need to be able to enter the "Insured Amount" at the top 20 million dollars "20000000" (as an example because it will populate almost all possible fields that will have a comma separated values with a decimal place)

Can anyone end my misery? Thanks for any help.

like image 588
Zack Bluem Avatar asked Nov 21 '25 16:11

Zack Bluem


1 Answers

After trying many different solutions, this seems (to me) the best way:

JS Fiddle demo

(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 2});

or

var opts = '{style: "decimal", currency: "USD", minimumFractionDigits: 2}';
(1234568).toLocaleString("en-US", opts);

or

(1234568).toLocaleString("en-US", {style: "decimal", minimumFractionDigits: 0});

I liked NickG's comment from mid-2013: "Agreed, it's not fully supported across all browsers (yet), but it's still a solution. (And arguably the most valid solution, as its forward compatible with the non-supported browsers, and it's a documented feature of the JavaScript api.)"

Sources:

How to format numbers as currency strings

How to format a number with commas as thousands separators?

like image 156
crashwap Avatar answered Nov 23 '25 05:11

crashwap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!