使用Javascript以印度格式显示数字

时间:2013-04-16 12:32:32

标签: javascript jquery number-systems

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

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

获得此输出:125,465,778

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

请帮我解决这个问题。

16 个答案:

答案 0 :(得分:48)

对于整数:

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

浮动:

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

答案 1 :(得分:38)

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

您可以使用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'
});
// → Rs.123,456.79

<div id="result"></div>
<div id="result1"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:16)

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

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

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

答案 3 :(得分:6)

给定一个低于函数的数字,它以印度格式的数字分组返回格式化数字。

  

ex:输入:12345678567545.122343

     

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

答案 4 :(得分:3)

这应该有用。

AP.define

你也可以通过defualt传递函数内部的参数,它将采用国际惯例。 如果你想使用印度惯例,你应该这样写。

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

但此代码仅适用于Chrome,Mozzilla和IE。 它不会在Safari上工作。

答案 5 :(得分:2)

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

即可

然后您只需要:

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

答案 6 :(得分:2)

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

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

答案 7 :(得分:1)

最简单的方法就是使用Globalize插件(详细了解herehere):

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

答案 8 :(得分:1)

尝试如下,我在这里找到了一个数字格式化插件: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

答案 9 :(得分:1)

简单的方法,

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

答案 10 :(得分: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;
}

此函数会将所有函数转换为float,因为它是

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

答案 11 :(得分:1)

只需使用 .toLocaleString('en-IN')

console.log(Number(125465778).toLocaleString('en-IN')) //打印12,54,65,778

答案 12 :(得分:0)

基于Nidhinkumar's question我检查了上述答案和 处理负数时输出不会是正确的,例如:-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('');

答案 13 :(得分: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;
        return result;
    }

答案 14 :(得分:0)

上面改进的Slopen方法适用于int和float。

 
 
 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 :(得分: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")
        });
    });
})