Displaying a number in Indian format using Javascript
Asked Answered
S

17

59

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 .

Scurry answered 16/4, 2013 at 12:32 Comment(4)
What's the logic of the desired output ? One comma every 2 digits apart at the end ?Gilreath
yes, It is indian numbering systemScurry
Can it have decimal point in it ?Affirm
what about 100 crore and 1000 crore.. anybody with a solution for that?Leila
T
70

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

Trihedron answered 16/4, 2013 at 12:55 Comment(3)
your answer returns -,123 when the input number is -123Moneyed
it returns 1,23,45,67,89,01,234.154 when I input 12345678901234.155Haywoodhayyim
it returns -32,651.75 when passing -32650.75Endless
M
112

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>
Myocardium answered 18/11, 2015 at 12:36 Comment(2)
excellent. I didn't know such standard existed and with a good browser support.Variable
If your value is in string i.e. "123456.789" make sure to convert this to number before calling. i.e. Number(number).toLocaleString('en-IN')Monniemono
T
70

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

Trihedron answered 16/4, 2013 at 12:55 Comment(3)
your answer returns -,123 when the input number is -123Moneyed
it returns 1,23,45,67,89,01,234.154 when I input 12345678901234.155Haywoodhayyim
it returns -32,651.75 when passing -32650.75Endless
N
30

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

Necrophilia answered 9/4, 2016 at 13:38 Comment(3)
Your answer may help for me. but fine tune your answer as most faster and performance wellApish
Incomplete solution |XXX| numberWithCommas(12345.32) = > "1,23,45,.32" |XXX| numberWithCommas(12345222.32) => "12,34,52,22,.32" |XXX| numberWithCommas(45.32) => "45,.32" |XXX| numberWithCommas(45) => ",45"Lashandralashar
Kudos to Solution Number 2. I am going to use it for all my development.Sparse
L
25

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"
Landin answered 3/10, 2014 at 20:2 Comment(0)
L
9

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/

Lashandralashar answered 31/8, 2015 at 9:37 Comment(0)
L
8

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));
Laux answered 6/2, 2019 at 6:11 Comment(1)
to use it in react-native, simply install a polyfill of intl and boom, good to goLaux
U
2

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');
Unlimited answered 16/4, 2013 at 12:57 Comment(0)
P
2

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
Pangolin answered 16/4, 2013 at 13:35 Comment(0)
E
2

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

Then all you need is:

OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); 
// Returns ₹ 25,34,234.00
Errolerroll answered 26/10, 2017 at 17:50 Comment(0)
E
2

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)

Eldoraeldorado answered 3/9, 2021 at 9:46 Comment(0)
A
1

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;
}
Aesthetic answered 14/9, 2016 at 10:1 Comment(0)
T
1

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
Tiatiana answered 27/9, 2019 at 7:31 Comment(0)
M
0

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('');
Maibach answered 23/9, 2017 at 16:0 Comment(0)
V
0

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))
Vexillum answered 27/9, 2019 at 7:11 Comment(0)
R
0

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")
        });
    });
})
Resurrection answered 24/11, 2019 at 9:44 Comment(0)
D
0

You can use Intl.NumberFormat for formatting numbers to Indian format. Here is an Example below:

const number = 12345678;

const formatedNumber = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(number);

console.log(formatedNumber)
// Expected output: "₹1,23,45,678.00"

Reference

Drowse answered 7/9, 2023 at 14:17 Comment(1)
There are already multiple answers saying that, e.g. https://mcmap.net/q/326912/-displaying-a-number-in-indian-format-using-javascriptPopup
K
0

In some cases where padding of additional 0's are necessary even though the number is a whole number, you can add the minimumFractionDigits: 2 option to set minimum 2 digits.

let price = 784000;
let cost = 12750000.5

price.toLocaleString('en-IN');
cost.toLocaleString('en-IN');

//price → 7,84,000
//cost → 1,27,50,000.5

price.toLocaleString('en-IN', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
cost.toLocaleString('en-IN', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
//price → 7,84,000.00
//cost → 1,27,50,000.50
Kameko answered 26/10, 2023 at 11:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.