53

我有以下代码要在印度编号系统中显示。

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

我得到这个输出:125,465,778

我需要这样的输出:12,54,65,778.

请帮我解决这个问题。

4

15 回答 15

86

我迟到了,但我想这会有所帮助:)

你可以使用Number.prototype.toLocaleString()

句法

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>

于 2015-11-18T12:36:30.717 回答
67

对于整数:

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

现场演示

对于浮动:

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

现场演示

于 2013-04-16T12:55:03.640 回答
27

简单的做法,

1. 使用 LocalString() 的直接方法

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

2. 使用 Intl - 国际化 API

Intl对象是 ECMAScript 国际化 API 的命名空间,它提供语言敏感的字符串比较、数字格式以及日期和时间格式。

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

3.使用自定义功能:

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

如果您的输入是 10000.5,

numberWithCommas(10000.5)

你会得到这样的输出,10,000.5

于 2016-04-09T13:38:52.713 回答
24

仅对于整数不需要额外的操作。

这将匹配最后的每个数字,后面有 1 个或多个双位数模式,并将其替换为自身 +“,”:

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

但是由于我们希望最后有 3,让我们通过在输入匹配结束前添加额外的“\d”来明确说明这一点:

"125465778".replace(/(\d)(?=(\d\d)+\d$)/g, "$1,");
-> "12,54,65,778"
于 2014-10-03T20:02:33.520 回答
9

给定以下函数的数字,它以印度数字分组格式返回格式化数字。

例如:输入:12345678567545.122343

输出: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/

于 2015-08-31T09:37:15.400 回答
5

我在比赛中有点晚了。但这是执行此操作的隐含方式。

var number = 3493423.34;

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

如果您不想要货币符号,请像这样使用它

console.log(new Intl.NumberFormat('en-IN').format(number));
于 2019-02-06T06:11:39.873 回答
2

最简单的方法就是使用Globalize插件(在此处此处阅读有关它的更多信息):

var value = 125465778;
var formattedValue = Globalize.format(value, 'n');
于 2013-04-16T12:57:34.883 回答
2

尝试如下,我在这里找到了一个数字格式化插件:Java script number Formatter

通过使用我已经完成了以下代码,它工作正常,试试这个,它会帮助你..

脚本 :

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

输入:

1) 125465778
2) 1234567.89

输出:

1) 12,54,65,778
2) 12,34,567.89
于 2013-04-16T13:35:32.850 回答
2

只需使用https://osrec.github.io/currencyFormatter.js/

那么你只需要:

OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); 
// Returns ₹ 25,34,234.00
于 2017-10-26T17:50:32.630 回答
1

此函数可以正确处理浮点值,只是添加到另一个答案

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

此函数会将所有函数原样转换为浮点数

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;
}
于 2016-09-14T10:01:42.143 回答
1

上面即兴的 Slopen 方法,适用于 int 和 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

于 2019-09-27T07:31:23.603 回答
1

这些将格式化相应系统中的值。

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

对于美国数字系统(百万和十亿)

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

对于印度数字系统(十亿和千万)

于 2021-09-03T09:46:15.290 回答
0

根据Nidhinkumar 的问题,我检查了上述答案,在处理负数时,输出将不正确,例如:-300 它应该显示为 -300 但上述答案将显示为 -,300 这不好所以我已尝试使用以下代码,即使在负面情况下也可以使用。

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('');
于 2017-09-23T16:00:30.103 回答
0

通过小数支持和测试用例即兴创作@slopen 的答案。

用法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")
        });
    });
})
于 2019-11-24T09:44:11.420 回答
0

印度货币格式功能

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

于 2019-09-27T07:11:32.380 回答