-3

I am getting an input string containing digits with comma (,) separated like these formats

1) X,X

2) X,XX

3) XX,X

My desired format is XX,XX.

I want if I get the input string like in above 1,2,3 formats it should be formatted as my desired format XX,XX.

For example,

1) If I get a string in this format 1,12. I want to put a zero before 1 like this 01,12.

2) If I get a string in this format 1,1. I want to put a zero before and ofter 1 like this 01,10.

3) If I get a string in this format 11,1. I want to put a zero after the last 1 like this 11,10.

Any help will be highly appreciated, thanks in advance.

4
  • post what have you tried so far Commented Nov 21, 2014 at 14:52
  • 1
    possible duplicate of java decimal String format Commented Nov 21, 2014 at 14:52
  • You want to just display this String or also use it inside a variable? Commented Nov 21, 2014 at 14:54
  • I am using comma not dot that decimal format will not work for me. Commented Nov 21, 2014 at 15:11

4 Answers 4

0

You can use regex pattern to format in your specific pattern using Lookaround

(?=^\d,\d\d$)|(?<=^\d\d,\d$)|(?<=^\d,\d$)|(?=^\d,\d$)

Online demo

Here we are using three combination of data as given by you and empty space is replaced by zero.

Sample code:

String regexPattern="(?=^\\d,\\d\\d$)|(?<=^\\d\\d,\\d$)|(?<=^\\d,\\d$)|(?=^\\d,\\d$)";
System.out.println("1,12".replaceAll(regexPattern, "0"));
System.out.println("1,1".replaceAll(regexPattern, "0"));
System.out.println("11,1".replaceAll(regexPattern, "0"));

output:

01,12
01,10
11,10
Sign up to request clarification or add additional context in comments.

Comments

0

Feed in your number to the function, and get the desired String result.

    public  static String convert(String s){
    String arr[] = s.split(",");

    if(arr[0].length()!=2){
        arr[0] = "0"+arr[0];
    }

    if(arr[1].length()!=2){
        arr[1] = arr[1]+"0";
    }

    return arr[0]+","+arr[1];

}

But it only works in the format described above.

Comments

0

If your goal is to print these strings, you could use the format method, and leading and trailing zeroes.

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Comments

0
Object[] splitted = input.split(",");
System.out.println(String.format("%2s,%-2s", splitted).replace(' ','0'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.