有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在字符串数学中的数字中加了一个逗号

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

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

但由于存在运算符“+-…”而导致获取错误


共 (2) 个答案

  1. # 1 楼答案

    您可以尝试以下代码:

    我正在使用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)
    
  2. # 2 楼答案

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