String format issue

I have two String data this way


Expected Output:

output x="123456,789"
output y="123456,789.09"

What is the  easy way to do this ?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kanti PrasadCommented:

To avoid confusion try
String xformatted = x.substring(0,6) + "," + x.substring(6,9)
String yformatted = y.substring(0,6) + "," + y.substring(6,12)
x = xformatted
y = yformatted
cofactorAuthor Commented:
those are sample input.

you should not fix 6 in your code.

input = ="3456,789"
output ="3456,789"

your code wont work...more generic solution required.

idea is to put comma in the 1000th place as shown above
Kanti PrasadCommented:

Sorry are you looking to get the length of x and y and then put commas in respective places ?

As I just counted the outputs you want above for x and y and just appended the comma in the position you wanted.  

 x.substring(Start from left position i.e 1,End at 6 place) + "," + x.substring(after appending comma Start from 7 position,Till end i.e 9)
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

Just an observation, why are you holding a number as a String?
Kanti PrasadCommented:

double  x= 123456789
double y= 123456789.09

If you declare as above then the easiest way will be by importing
import java.text.NumberFormat;
import java.util.Locale;

 System.out.println(NumberFormat.getNumberInstance(Locale.US).format(x)); System.out.println(NumberFormat.getNumberInstance(Locale.US).format(y));
Kanti PrasadCommented:

If you are keen to use only String then the below code will help
          String  x= "123456789";
         String y= "123456789.09" ;
         double xtodub = Double.parseDouble(x);
        double ytodub = Double.parseDouble(y);
cofactorAuthor Commented:
It did not work,...

Your code is giving   output  123,456,789

Whereas I asked output as    123456,789

What is the fix ?
Kanti PrasadCommented:

I am not sure of your exact requirement.

For the first input and output you posted the below code will work if those values are of that same lengths.

String xformatted = x.substring(0,6) + "," + x.substring(6,9)
String yformatted = y.substring(0,6) + "," + y.substring(6,12)

If your x and y length of digits  change always then  you need to get their lengths.
If your x value will also have some time decimals then you need to search for the . (point) and if the decimal is there then you need the v value to be 5 instead of 3 by using a if loop.

  String x = "123456789";
        String y = "123456789.09";
        int l = 0;
        int v = 0;
        l = x.length();
        v = l-3;
        String xformatted = x.substring(0, v) + "," + x.substring(v, 9);
        String yformatted = y.substring(0, v) + "," + y.substring(v, 12);
Why are you holding a number as a String?
mccarlIT Business Systems Analyst / Software DeveloperCommented:
I don't think you can get the NumberFormat classes to only do thousands separators (and not millions, etc). So easiest bet might be just to fiddle with Strings, as much as you should try not to do that...

    public void testStringNumbers(){

    private String format(String num) {
        if (num.indexOf(',') >= 0) {
            return num;
        int decPos = num.lastIndexOf('.');
        if (decPos == -1) {
            decPos = num.length();
        if (decPos > 3) {
            return num.substring(0, decPos - 3) + "," + num.substring(decPos - 3);
        return num;

Open in new window

Kanti PrasadCommented:

Try with "contains" and you will always get a comma on the place you are looking for even if the string lengths change.
If you have more than x and y values then put that code into a function and return v and len values for all your strings with numbers.
        String x = "123456789";
        String y = "123456789.09";
        int xlen = 0;
        int ylen = 0 ;
        int v = 0;
        xlen = x.length();
        ylen = y.length();
        boolean decx =x.contains(".");
        boolean decy = y.contains(".");
        if (decx)  v = xlen-5 ;
        else   v = xlen-3;
        String xformatted = x.substring(0, v) + "," + x.substring(v, xlen);
        v = 0;
        if (decy) v = ylen - 5 ;
                else v = ylen - 3;
        String yformatted = y.substring(0, v) + "," + y.substring(v, ylen);
        System.out.println("xformatted = " + xformatted);
        System.out.println("yformatted = " + yformatted);

Open in new window

Jim CakalicSenior Developer/ArchitectCommented:
Using apache.commons.lang3.StringUtils:
public String insertComma(String val) {
    int at = (val.contains(".") ? val.lastIndexOf('.') : val.length()) - 3;
    return at <= 0 ? val : StringUtils.left(val, at) + "," + StringUtils.right(val, val.length() - at);

Open in new window

Using the String.replaceAll with a regex:
public String insertComma(String val) {
    return val.replaceAll("^([0-9]+)([0-9]{3})(\\.{1}[0-9]+){0,1}$", "$1,$2$3");

Open in new window

Both appear to work correctly giving these output with the specified inputs:
123456789.09 -> 123456,789.09
123456789 -> 123456,789
123.09 -> 123.09
123 -> 123
12 -> 12
though both are currently susceptible to throwing NPE when passed null.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
awking00Information Technology SpecialistCommented:
Similar to Jim's first solution using StringBuilder in place of StringUtils -
public static String addComma(String str) {
            StringBuilder sb = new StringBuilder(str);
            boolean hasDot = false;
            if (sb.indexOf(".") >= 0) {hasDot = true;}
            return hasDot && sb.indexOf(".") > 3 ? sb.insert(sb.indexOf(".") - 3, ",").toString() : !hasDot && sb.length() > 3 ? sb.insert(sb.length() - 3, ",").toString() : sb.toString();
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.