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