一尘不染

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

javascript

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

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

正在获取此输出:125,465,778

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

请帮我解决这个问题。


阅读 338

收藏
2020-05-01

共1个答案

一尘不染

对于整数:

    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);
2020-05-01