Wednesday, 28 September 2016

Format the number in US Format in JavaScript

To get the number in US number format, we may use jQuery Globalization. But for a simple formatting like this, we may not need to include that library.
Just use the given function that will return number in the US format.
        function getFormattedNumber(number, isPrecision) {
            var isPrecision = typeof isPrecision != 'undefined' ? isPrecision : true; 
            if(isPrecision) {
                return number.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            } else {
                return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }
        }
    
If you don't need precision call the function with the precision false.
        getFormattedNumber(12345.25, false);
    
If the precision is need then set the precision with true or don't set that field, the default is true.
        getFormattedNumber(12345.25);
    

No comments:

Post a Comment