2

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Zack Bluem
  • 83
  • 1
  • 2
  • 11
  • You're saying none of the methods in [this question](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) work? The one with 450+ votes seems to work after testing quickly. – numbers1311407 Oct 29 '13 at 17:22
  • There's also [toLocaleString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) – numbers1311407 Oct 29 '13 at 17:30

3 Answers3

9

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

jsFiddle 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:

jsFiddle Demo

How can I format numbers as money in JavaScript?

How to print a number with commas as thousands separators in JavaScript

Community
  • 1
  • 1
crashwap
  • 2,846
  • 3
  • 28
  • 62
2

You could have provided some inputs and corresponding outputs to describe your problem clearer. I assume you need a function that gets as input any non-negative number and want as output a string formatted with decimal point and thousand-separators. If my assumption is true the following might help you, tested on firefox 24.0 /Linux:

<!DOCTYPE html>
<html>
<head>
    <title>HTML</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        var decimalSeparator = ".";
        var decimalDefault = decimalSeparator + "00";
        var thousandsSeparator = ",";

        /**
         * @param {String or Number} value The value to format
         * @returns {String} The formatted Number as a String
         */
        function formatMoney(value) {
            var valueStr = String(value);
            var decimalDividerPos = valueStr.indexOf(".");
            var decimalPart = decimalDividerPos == -1 ? decimalDefault : decimalSeparator + valueStr.substr(decimalDividerPos + 1);
            var integerPart = decimalDividerPos == -1 ? valueStr : valueStr.substring(0, decimalDividerPos);
            var integerAry = new Array();
            var lenTemp = 0;
            for (var i = integerPart.length - 1; i >= 0; i--) {
                integerAry.unshift(integerPart.substr(i, 1));
                if (i && (!(++lenTemp % 3))) {
                    integerAry.unshift(thousandsSeparator);
                }
            }
            return integerAry.join("") + decimalPart;
        }
    </script>
<body>
    <script type="text/javascript">
        var testValues = new Array(
                0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
                0.9876, 1.9876, 10.9876, 100.9876, 1000.9876, 10000.9876, 100000.9876, 1000000.9876, 10000000.9876,
                1234567e+123, Number.MAX_VALUE);
        for (var x in testValues) {
            console.log("VALUE=" + testValues[x] + " =>  FORMATTED=" + formatMoney(testValues[x]));
        }
    </script>
</body>
</html>
Michael Besteck
  • 2,415
  • 18
  • 10
0

I'm guessing your problem is while doing math, not while formatting values.

The value that you get from text fields is of type 'string'. When you do math on simple strings Javascript will automatically coerce them to numbers for you. But once you add formatting this auto-conversion breaks.

console.log('5000' - '2000'); // outputs the value 3000 of type number
console.log('5,000' - '2,000'); // outputs NaN - this is an invalid format for auto-conversion to numbers

Once you are formatting your values in the text fields you have to treat them as strings. In order to do math you have to parse them back into numbers.

Something like:

function parseCommaSeparated( strVal ) {
    return parseFloat(strVal.replace(',','');) // remove commas before parse
}
Mike Edwards
  • 3,742
  • 17
  • 23