当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - I need Indian currency format like 100000 as 1,00,000 , 1234 as 1,234

问题描述:

I need Indian currency format like 100000 as 1,00,000 , 1234 as 1,234.

I have tried this code,

function currencyFormat1(id) {

var x;

x = id.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;

return res;

}

But it is working in only java script,

I need this as core java code , I have tried to convert this but the

var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;

网友答案:

In Java regular expression syntax is slightly different. /\B(?=(\d{2})+(?!\d))/g, would need to become "?g\\B(?=(\\d{2})+(?!\\d))".

网友答案:

The java syntax would roughly be the following.

Note that I used the regex given by npinti in his/her answer :

public String currencyFormat1(Object id) {
                            String x;
                            x = id.toString();
                            String lastThree = x.substring(x.length() - 3);
                            String otherNumbers = x.substring(0, x.length() - 3);
                            if (!otherNumbers.isEmpty())
                                lastThree = "," + lastThree;
                            String res = otherNumbers.replaceAll("?g\\B(?=(\\d{2})+(?!\\d))", ",") + lastThree;
                            return  res;
                        }
网友答案:

The Java NumberFormat will give you what you want, but you can also write your own method:

public static String fmt(String s){

    String formatted = "";
    if(s.length() > 1){
        formatted = s.substring(0,1);
        s = s.substring(1);
    }

    while(s.length() > 3){
        formatted += "," + s.substring(0,2);
        s = s.substring(2);
    }
    return formatted + "," + s + ".00"; 
}

Test:

System.out.println(fmt("1234"));
System.out.println(fmt("100000"));
System.out.println(fmt("12345678"));
System.out.println(fmt("123456789"));                       
System.out.println(fmt("1234567898"));

Output:

1,234.00
1,00,000.00
1,23,45,678.00
1,23,45,67,89.00
1,23,45,67,898.00
网友答案:

In Java you can also use DecimalFormat:

double val = Double.parseDouble(num);  //If your num is in String  
DecimalFormat fmt = new DecimalFormat("#,###.00");
System.out.println(fmt.format(val));
网友答案:

$('#textfield').keyup(function() {
var value=$('#textfield').val();
      
      var newvalue=value.replace(/,/g, '');   
      var valuewithcomma=Number(newvalue).toLocaleString('en-IN'); 
      $('#textfield').val(valuewithcomma); 

      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<form><input type="text" id="textfield" ></form>
分享给朋友:
您可能感兴趣的文章:
随机阅读: