Displaying a number in Indian format using Javascript

JavascriptJqueryNumber Systems

Javascript Problem Overview


I have the following code to display in Indian numbering system.

 var x=125465778;
 var res= x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

Am getting this output :125,465,778.

I need output like this: 12,54,65,778.

Please help me to sort out this problem .

Javascript Solutions


Solution 1 - Javascript

i'm late but i guess this will help :)

you can use Number.prototype.toLocaleString()

Syntax

numObj.toLocaleString([locales [, options]])

var number = 123456.789;
// India uses thousands/lakh/crore separators
document.getElementById('result').innerHTML = number.toLocaleString('en-IN');
// → 1,23,456.789

document.getElementById('result1').innerHTML = number.toLocaleString('en-IN', {
    maximumFractionDigits: 2,
    style: 'currency',
    currency: 'INR'
});
// → ₹1,23,456.79

<div id="result"></div>
<div id="result1"></div>

Solution 2 - Javascript

For Integers:

    var x=12345678;
    x=x.toString();
    var lastThree = x.substring(x.length-3);
    var otherNumbers = x.substring(0,x.length-3);
    if(otherNumbers != '')
        lastThree = ',' + lastThree;
    var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
    alert(res);

Live Demo

For float:

    var x=12345652457.557;
    x=x.toString();
    var afterPoint = '';
    if(x.indexOf('.') > 0)
       afterPoint = x.substring(x.indexOf('.'),x.length);
    x = Math.floor(x);
    x=x.toString();
    var lastThree = x.substring(x.length-3);
    var otherNumbers = x.substring(0,x.length-3);
    if(otherNumbers != '')
        lastThree = ',' + lastThree;
    var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
    
    alert(res);

Live Demo

Solution 3 - Javascript

Simple way to do,

1. Direct Method using LocalString()

(1000.03).toLocaleString()
(1000.03).toLocaleString('en-IN') # number followed by method

2. using Intl - Internationalization API

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.

eg: Intl.NumberFormat('en-IN').format(1000)

3. Using Custom Function:

function numberWithCommas(x) {
    return x.toString().split('.')[0].length > 3 ? x.toString().substring(0,x.toString().split('.')[0].length-3).replace(/\B(?=(\d{2})+(?!\d))/g, ",") + "," + x.toString().substring(x.toString().split('.')[0].length-3): x.toString();
}

console.log("0 in indian format", numberWithCommas(0));
console.log("10 in indian format", numberWithCommas(10));
console.log("1000.15 in indian format", numberWithCommas(1000.15));
console.log("15123.32 in indian format", numberWithCommas(15123.32));

if your input is 10000.5,

numberWithCommas(10000.5)

You will get output like this, 10,000.5

Solution 4 - Javascript

For integers only no additional manipulations needed.

This will match every digit from the end, having 1 or more double digits pattern after, and replace it with itself + ",":

"125465778".replace(/(\d)(?=(\d\d)+$)/g, "$1,");
-> "1,25,46,57,78"

But since we want to have 3 in the end, let's state this explicitly by adding extra "\d" before match end of input:

"125465778".replace(/(\d)(?=(\d\d)+\d$)/g, "$1,");
-> "12,54,65,778"

Solution 5 - Javascript

Given a number to below function, it returns formatted number in Indian format of digit grouping.

> ex: input: 12345678567545.122343 > > output: 1,23,45,67,85,67,545.122343

    function formatNumber(num) {
            input = num;
            var n1, n2;
            num = num + '' || '';
            // works for integer and floating as well
            n1 = num.split('.');
            n2 = n1[1] || null;
            n1 = n1[0].replace(/(\d)(?=(\d\d)+\d$)/g, "$1,");
            num = n2 ? n1 + '.' + n2 : n1;
            console.log("Input:",input)
            console.log("Output:",num)
            return num;
    }
    
    formatNumber(prompt("Enter Number",1234567))
    
    

https://jsfiddle.net/scLtnug8/1/

Solution 6 - Javascript

I am little late in the game. But here is the implicit way to do this.

var number = 3493423.34;

console.log(new Intl.NumberFormat('en-IN', { style: "currency", currency: "INR" }).format(number));

if you dont want currency symbol, use it like this

console.log(new Intl.NumberFormat('en-IN').format(number));

Solution 7 - Javascript

The easiest way is just to use Globalize plugin (read more about it here and here):

var value = 125465778;
var formattedValue = Globalize.format(value, 'n');

Solution 8 - Javascript

Try like below, I have found a number formatter Plugin here : Java script number Formatter

By using that i have done the below code, It works fine, Try this, It will help you..

SCRIPT :

<script src="format.20110630-1100.min.js" type="text/javascript"></script>

<script>
  var FullData = format( "#,##0.####", 125465778)
  var n=FullData.split(",");
  var part1 ="";
    for(i=0;i<n.length-1;i++)
    part1 +=n[i];
  var part2 = n[n.length-1]
  alert(format( "#0,#0.####", part1) + "," + part2);
</script>

Inputs :

1) 125465778
2) 1234567.89

Outputs :

1) 12,54,65,778
2) 12,34,567.89

Solution 9 - Javascript

Simply use https://osrec.github.io/currencyFormatter.js/

Then all you need is:

OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); 
// Returns ₹ 25,34,234.00

Solution 10 - Javascript

This function can handle float value properly just addition to another answer

function convertNumber(num) {
  var n1, n2;
  num = num + '' || '';
  n1 = num.split('.');
  n2 = n1[1] || null;
  n1 = n1[0].replace(/(\d)(?=(\d\d)+\d$)/g, "$1,");   
  num = n2 ? n1 + '.' + n2 : n1;
  n1 = num.split('.');
  n2 = (n1[1]) || null;
  if (n2 !== null) {
           if (n2.length <= 1) {
                   n2 = n2 + '0';
           } else {
                   n2 = n2.substring(0, 2);
           }
   }
   num = n2 ? n1[0] + '.' + n2 : n1[0];

   return num;
}

this function will convert all function to float as it is

function formatAndConvertToFloatFormat(num) {
  var n1, n2;
  num = num + '' || '';
  n1 = num.split('.');
  if (n1[1] != null){
    if (n1[1] <= 9) {
       n2 = n1[1]+'0';
    } else {
       n2 = n1[1]
    }
  } else {
     n2 = '00';
  }
  n1 = n1[0].replace(/(\d)(?=(\d\d)+\d$)/g, "$1,");
  return  n1 + '.' + n2;
}

Solution 11 - Javascript

Improvised Slopen's approach above, Works for both int and floats.

 function getIndianFormat(str) { 
  str = str.split(".");
  return str[0].replace(/(\d)(?=(\d\d)+\d$)/g, "$1,") + (str[1] ? ("."+str[1]): "");

}

 console.log(getIndianFormat("43983434")); //4,39,83,434
 console.log(getIndianFormat("1432434.474")); //14,32,434.474

Solution 12 - Javascript

These will format the value in the respective systems.

$(this).replace(/\B(?=(?:\d{3})+(?!\d))/g, ','); 

> For US number system (millions & billions)

$(this).replace(/\B(?=(?:(\d\d)+(\d)(?!\d))+(?!\d))/g, ',');

> For Indian number system (lakhs & crores)

Solution 13 - Javascript

Based on Nidhinkumar's question i have checked the above answers and while handling negative numbers the output won't be correct for eg: -300 it should display as -300 but the above answers will display it as -,300 which is not good so i have tried with the below code which works even during the negative cases.

var negative = input < 0;
    var str = negative ? String(-input) : String(input);
    var arr = [];
    var i = str.indexOf('.');
    if (i === -1) {
      i = str.length;
    } else {
      for (var j = str.length - 1; j > i; j--) {
        arr.push(str[j]);
      }
      arr.push('.');
    }
    i--;
    for (var n = 0; i >= 0; i--, n++) {
      if (n > 2 && (n % 2 === 1)) {
        arr.push(',');
      }
      arr.push(str[i]);
    }
    if (negative) {
      arr.push('-');
    }
    return arr.reverse().join('');

Solution 14 - Javascript

Indian money format function

   function indian_money_format(amt)
    	{		
    		amt=amt.toString();
    		var lastThree = amt.substring(amt.length-3);
    		var otherNumbers = amt.substring(0,amt.length-3);
    		if(otherNumbers != '')
    			lastThree = ',' + lastThree;
    		var result = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
        alert(result)
    		return result;
    	}
      
      indian_money_format(prompt("Entry amount",123456))

Solution 15 - Javascript

Improvising @slopen's answer with decimal support and test cases.

Usage: numberToIndianFormat(555555.12) === "5,55,555.12"

utils.ts

export function numberToIndianFormat(x: number): string {
    if (isNaN(x)) {
        return "NaN"
    } else {
        let string = x.toString();
        let numbers = string.split(".");
        numbers[0] = integerToIndianFormat(parseInt(numbers[0]))
        return numbers.join(".");
    }
}
function integerToIndianFormat(x: number): string {
    if (isNaN(x)) {
        return "NaN"
    } else {
        let integer = x.toString();
        if (integer.length > 3) {
            return integer.replace(/(\d)(?=(\d\d)+\d$)/g, "$1,");
        } else {
            return integer;
        }
    }
}

utils.spec.ts

describe('numberToIndianFormat', () => {
    it('nan should output NaN', () => {
        expect(numberToIndianFormat(Number.NaN)).toEqual("NaN")
    });
    describe('pure integer', () => {
        it('should leave zero untouched', () => {
            expect(numberToIndianFormat(0)).toEqual("0")
        });
        it('should leave simple numbers untouched', () => {
            expect(numberToIndianFormat(10)).toEqual("10")
        });
        it('should add comma at thousand place', () => {
            expect(numberToIndianFormat(5555)).toEqual("5,555")
        });
        it('should add comma at lakh place', () => {
            expect(numberToIndianFormat(555555)).toEqual("5,55,555")
        });
        it('should add comma at crore place', () => {
            expect(numberToIndianFormat(55555555)).toEqual("5,55,55,555")
        });
    });
    describe('with fraction', () => {
        it('should leave zero untouched', () => {
            expect(numberToIndianFormat(0.12)).toEqual("0.12")
        });
        it('should leave simple numbers untouched', () => {
            expect(numberToIndianFormat(10.12)).toEqual("10.12")
        });
        it('should add comma at thousand place', () => {
            expect(numberToIndianFormat(5555.12)).toEqual("5,555.12")
        });
        it('should add comma at lakh place', () => {
            expect(numberToIndianFormat(555555.12)).toEqual("5,55,555.12")
        });
        it('should add comma at crore place', () => {
            expect(numberToIndianFormat(55555555.12)).toEqual("5,55,55,555.12")
        });
    });
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontilakView Question on Stackoverflow
Solution 1 - JavascriptTushar Gupta - curioustusharView Answer on Stackoverflow
Solution 2 - JavascriptPrasath KView Answer on Stackoverflow
Solution 3 - JavascriptMohideen bin MohammedView Answer on Stackoverflow
Solution 4 - JavascriptslopenView Answer on Stackoverflow
Solution 5 - JavascriptD P VenkateshView Answer on Stackoverflow
Solution 6 - JavascriptshubhamkesView Answer on Stackoverflow
Solution 7 - JavascripttpeczekView Answer on Stackoverflow
Solution 8 - JavascriptPandianView Answer on Stackoverflow
Solution 9 - JavascriptVaibhav KhullarView Answer on Stackoverflow
Solution 10 - JavascriptYatender SinghView Answer on Stackoverflow
Solution 11 - JavascriptMurali NepalliView Answer on Stackoverflow
Solution 12 - JavascriptpgksunilkumarView Answer on Stackoverflow
Solution 13 - JavascriptNidhin KumarView Answer on Stackoverflow
Solution 14 - JavascriptLove KumarView Answer on Stackoverflow
Solution 15 - Javascriptamit77309View Answer on Stackoverflow