Thousands separator in a number string

Hello All,

Thank you in advance for any replies.  This forum has a been a great resource to getting my little widget up and running.  I'm not a terribly experienced developer outside of VB so sorry if this is obvious.  I searched the forum and didn't really come across a solution.

Basic idea is I'm retrieving a dollar value from an API.  I've got this part down, and passed to a variable and formatted to give me 2 decimal points... 

My question is there a (preferably easy) way to add thousands separators? 

My 'price' is coming through as 4941515.1561531
I'm formatting it to get $ 4941515.16
What I would like for readability is $ 4,941,515.16

Ideas?  Thanks everyone!

function onReceivePrice(responseCode, data) {
        if(responseCode == 200) {
            Price = data["bpi"]["USD"]["rate_float"].toFloat();
            L1 = "$ "+Price.format("%.2f");
			L2 = "$ "+(Price*Port).format("%.2f");
          
        //! blah blah blah....

  • If you are supporting this language for multiple locales, this is a can of worms. Not all locales use comma as the decimal separator. Not all locales put the separator in the thousands place. Heck, not all locales use the $ symbol...

    If you don't care about that, you should be able to generate a string for the whole dollar amount, insert the separators, and then concatenate that with the fractional dollars.

    function format_money(dollar_sign, value, decimal_spacing, decimal_separator, decimal_point) {
        var whole = value.toNumber();
        var frac = ((value - whole) * 100).format("%02d");
    
        var digits = [];
        
        var count = 0;
        while (whole != 0) {
            var digit = (whole % 10).toString();
            whole /= 10;
            
            if (count == decimal_spacing) {
                digits.add(decimal_separator);
                count = 0;
            }
            ++count;
            
            digits.add(digit);
        }
        
        digits = digits.reverse();
        
        whole = "";
        for (var i = 0; i < digits.size(); ++i) {
            whole += digits[i];
        }
    
        return Lang.format("$1$ $2$$3$$4$", [ dollar_sign, whole, decimal_point, frac ]);
    }
    
    function format_money_us(value) {
        return format_money("$", value, 3, ",", ".");
    }

    This will be useful for some locales, but not all.

  • You are correct in that I am completely ignoring the language issues... this is more of a proof of concept and an mental exercise for me.  Your solution was EXACTLY what I was looking for. Thank you!