Javascript function required

I want to put comma in currency value.

Example: Here is the input and expected output

input
1234
output
1,234

input
1234567
output
1,234,567

input
123373.3333
output
123,373.33

I’m using

valuestring=valuestring.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, “$1,”);

but this code does not format 123373.3333=>123,373.33

How do I fix it ?

There a little JavaScript library called Numeral that will help you with all sorts of number formatting.

Is it not possible to do this without a library ?

Oh it is absolutely possible. If you don’t need any advanced formatting, just use this function

https://snipt.net/geekyjohn/format-number/


/**
 * Format a number
 *
 * @param {Number} num        The number to format
 * @param {Number} precision  Precision
 * @param {String} decimal    Decimal place operator
 * @param {String} thousand   Thousand place operator
 * @returns {String} Formatted number
 */
function formatNumber(num, precision, decimal, thousand) {
    "use strict";

    var sign, intVal, remain, final;

    precision = isNaN(precision = Math.abs(precision)) ? 2 : precision;
    decimal = decimal === undefined ? "." : decimal;
    thousand = thousand === undefined ? "," : thousand;

    sign = num < 0 ? "-" : "";
    intVal = parseInt(num = Math.abs(+num || 0).toFixed(precision), 10) + "";
    remain = (remain = intVal.length) > 3 ? remain % 3 : 0;

    final = sign;

    //the "prefix" numbers, before the first thousand operator
    final += remain ? intVal.substr(0, remain) + thousand : ""; 

    //place thousand operators every 3rd char
    final += intVal.substr(remain).replace(/(\\d{3})(?=\\d)/g, "$1" + thousand); 

    // set the correct decimal place operator + precision
    final += precision ? decimal + Math.abs(num - intVal).toFixed(precision).slice(2) : ""; 
    
    return final; 
}

// use like:
formatNumber(1234); //1,234.00
formatNumber(123.123432453, 3); // 123.123