3

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;
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Pradeep
  • 71
  • 1
  • 10
  • 3
    Have a look at this [SO answer "displaying-currency-in-indian-numbering-format"](http://stackoverflow.com/questions/5379231/displaying-currency-in-indian-numbering-format) – SubOptimal Dec 09 '15 at 08:31
  • 1
    Mind the gap between `java` and `javascript`. As we know, "One is essentially a toy, designed for writing small pieces of code, and traditionally used and abused by inexperienced programmers. The other is a scripting language for web browsers. " – xenteros Aug 03 '16 at 07:53

8 Answers8

2

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
user3437460
  • 17,253
  • 15
  • 58
  • 106
  • 1
    `1,23,45,67,89.00` This solution won't work. It starts formatting from the left hand side and at the end in hundreds it may leave just 2 digits. Also, if number is less than 999. – rajuGT Apr 24 '20 at 20:55
1

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

npinti
  • 51,780
  • 5
  • 72
  • 96
1

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;
                        }
Arnaud
  • 17,229
  • 3
  • 31
  • 44
0

$('#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>
0

Indian Currency Number Conversion RegExp

/(\d+?)(?=(\d\d)+(\d)(?!\d))(.\d+)?/g, "$1,"

$(this).val(parseFloat($(this).val(), 10).toFixed(2).replace(/(\d+?)(?=(\d\d)+(\d)(?!\d))(.\d+)?/g, "$1,").toString());

Foreign Currency Number Conversion RegExp

/(\d)(?=(\d{3})+.)/g, "$1,"

$(this).val(parseFloat($(this).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+.)/g, "$1,").toString());
Senthil Kumar
  • 145
  • 1
  • 4
0

Simple manual solutions might work if you only need 1 specific style for one specific locale (see other answers for this kind of solution). If not...

For Javascript, check out Globalize.

Install it

npm install globalize cldr-data --save

Then: (This particular example for Hindi, from an earlier answer here, remove the -native to have it only insert commas according to locale)

var cldr = require("cldr-data");
var Globalize = require("globalize");

Globalize.load(cldr("supplemental/likelySubtags"));
Globalize.load(cldr("supplemental/numberingSystems"));
Globalize.load(cldr("supplemental/currencyData"));

//replace 'hi' with appropriate language tag
Globalize.load(cldr("main/hi/numbers"));
Globalize.load(cldr("main/hi/currencies"));

//You may replace the above locale-specific loads with the following line,
// which will load every type of CLDR language data for every available locale
// and may consume several hundred megs of memory!
//Use with caution.
//Globalize.load(cldr.all());

//Set the locale
//We use the extention u-nu-native to indicate that Devanagari and
// not Latin numerals should be used.
// '-u' means extension
// '-nu' means number
// '-native' means use native script
//Without -u-nu-native this example will not work
//See 
// https://en.wikipedia.org/wiki/IETF_language_tag#Extension_U_.28Unicode_Locale.29
// for more details on the U language code extension 
var hindiGlobalizer = Globalize('hi-IN-u-nu-native');

var parseHindiNumber = hindiGlobalizer.numberParser();
var formatHindiNumber = hindiGlobalizer.numberFormatter();
var formatRupeeCurrency = hindiGlobalizer.currencyFormatter("INR");

console.log(parseHindiNumber('३,५००')); //3500
console.log(formatHindiNumber(3500));   //३,५००
console.log(formatRupeeCurrency(3500)); //₹३,५००.००

https://github.com/codebling/globalize-example

Codebling
  • 10,764
  • 2
  • 38
  • 66
-1

Code given by user3437460 is not working for all possible scenarios (EX:123456). Below code will work for all scenarios.

import java.util.Scanner;

public class INRFormat {

    public static String format(String num){
        System.out.println(num.length());
        String temp ="";
        //Removing extra '0's 
        while(num.substring(0,1).equals("0") && num.length()>1) {
            num = num.substring(1);
        }
        //Returning if it is 3 or less than 3 digits number.
        if(num.length()<=3){
            return num+".00";

        }
        //If it is an odd number then ',' will start after first digit(Ex: 1,23,456.00)
        else if(num.length()%2 !=0) {
            temp = num.substring(0, 2);
            num = num.substring(2);}
        //If it is an even number then ',' will start after first 2 digits(Ex: 12,34,567.00)
        else {
            temp = num.substring(0, 1);
            num = num.substring(1);
        }
        while (num.length() > 3) {
                temp += "," + num.substring(0, 2);
                num = num.substring(2);

            }

        return temp+","+num+".00";
    }
    public static void main(String args []){
         Scanner s =new Scanner(System.in);
         System.out.println("Please enter the number to be formatted:" );
         String num =s.nextLine();
         System.out.println("Formatted number:" + format(num));

    }

}
-2

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));
user3437460
  • 17,253
  • 15
  • 58
  • 106