Displaying a number in Indian format using Javascript

為{幸葍}努か 提交于 2019-11-26 02:56:24

问题


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 .


回答1:


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




回答2:


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'
});
// → Rs.123,456.79
<div id="result"></div>
<div id="result1"></div>



回答3:


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"



回答4:


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




回答5:


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) {
        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;
        return num;
}

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




回答6:


This should work.

var number=12345678;
alert(number.toLocaleString());

you can also pass the arguments inside the function here by defualt it will take international convention. If you wants to use indian convention then u should write it like this.

alert(number.toLocaleString("hi-IN"));

But this code will work only on Chrome, Mozzilla and IE. It won't work on Safari.




回答7:


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

Then all you need is:

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



回答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));



回答9:


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');



回答10:


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



回答11:


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;
}



回答12:


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('');



回答13:


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;
        return result;
    }



回答14:


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



回答15:


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")
        });
    });
})


来源:https://stackoverflow.com/questions/16037165/displaying-a-number-in-indian-format-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!