在字符串 math 内的数字中加上逗号

put a comma in the numbers just inside the string math

我有一串数学数字,我只想在数字中加一个逗号,例如:

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

我想将其发送到一个方法以将其转换为

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

我正在使用:

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

但是因为有运算符'+-..'所以得到错误

你可以试试这个代码:

我正在使用 str.toCharArray()

public static String parseResult(String str) {
    StringBuilder result = new StringBuilder();
    StringBuilder currentDigits = new StringBuilder();

    for (char ch: str.toCharArray()) {
        if (Character.isDigit(ch)) {
            currentDigits.append(ch);
        } else {
            if (currentDigits.length() > 0) {
                String output = String.format(Locale.US,"%,d", Long.parseLong(currentDigits.toString()));
                result.append(output);
                currentDigits = new StringBuilder();
            }
            result.append(ch);
        }
    }

    if (currentDigits.length() > 0)
        result.append(currentDigits.toString());

    return result.toString();
}

并调用函数:

    String s="(1000+2000000-5000÷90000+√5×80000)";
    Log.e("s", s);
    String result = parseResult(s);
    Log.e("result", result);

logcat :

E/s: (1000+2000000-5000÷90000+√5×80000)
E/result: (1,000+2,000,000-5,000÷90,000+√5×80,000)

使用 Matcher.appendReplacement 的简单方法还不够吗?

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();
}