java - 在数学字符串内的数字中添加逗号

标签 java android android-edittext

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

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

但是会出错,因为有运算符“+-..”

最佳答案

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

关于java - 在数学字符串内的数字中添加逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58345446/

相关文章:

android - 如何创建乐谱?

java - 如何从 Activity A 到 Activity B 显示seekBar值和选定的微调项目?

java - 监听器调用另一个监听器

java - 是否可以在 Google App Engine 中拥有具有同步访问功能的全局对象?

java - Spring Boot 中预定义的 bean

android - 在 Android 中更改编辑文本样式

android - 我可以得到编辑文本离开事件吗

java - 如何设置 apache jackrabbit 以使用 MySQL DB 来存储元数据并使用文件系统来存储与该元数据关联的文件

Android 模拟器 - 创建用户帐户时遇到问题

java - Android 中的图像切换问题