Search code examples
javaandroidandroid-edittext

put a comma in the numbers just inside the string math


I have a ٍstring of math numbers and I just want to put a comma in the numbers only for example:

String s="(1000+2000000-5000.8÷90000+√5×80000)";

I want to send it to a method to convert it to

String s="(1,000+2,000,000-5,000.8÷90,000+√5×80,000)";

i am using :

DecimalFormat myFormatter = new DecimalFormat("$###,###.###");
String output = myFormatter.format(s);
System.out.println(output);

But get it error because there are operator '+-..'


Solution

  • Isn't a simple approach using Matcher.appendReplacement enough?

    import java.text.DecimalFormat;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    ....
    
    static String formatMyString(String input){
        DecimalFormat myFormatter = new DecimalFormat("###,###.###");
        StringBuffer sb = new StringBuffer();
        Pattern p = Pattern.compile("(\\d+\\.*\\d+)");
        Matcher m = p.matcher(input);
        while(m.find()){
            String rep = myFormatter.format(Double.parseDouble(m.group()));
            m.appendReplacement(sb,rep);            
        }
        m.appendTail(sb);
        return sb.toString();
    }