java - 如何正确格式化数字字符串

标签 java string

我正在寻找一种有效的方法来正确设置数字String的格式,以便可以将其解析为double值。

要求:

  • 忽略不仅包含数字、逗号 (,) 或点 (.) 的字符串;
  • 重新格式化数字字符串,以便可以使用以下命令将其解析为 double 值: Double.parseDouble(numberString);
  • 当输入字符串无效时抛出 NumberFormatException

示例:1.234.567,89 => 1234567.89; 5 => 5; 6.3 => 6.3; 5.23 => 5.23;...

要检查String是否是数字,我想使用正则表达式或NumberUtils.isNumber(numberString)。后一个的唯一问题是它与“123,45”等字符串存在问题。

我当前的尝试(感觉效率很低):

    LOGGER.debug("Normalizing price string: " + price);
    String str = price;

    if (str.contains(",") || str.contains(".")) {

        int pos = -1;
        if (str.contains(",")) pos = str.lastIndexOf(',');
        else if (str.contains(".")) pos = str.lastIndexOf(".");

        //Remove all the dots and commas first
        str = str.replaceAll("[,.]", "");

        if (!NumberUtils.isNumber(str) || !NumberUtils.isDigits(str)) {
            LOGGER.debug("String does not match expected pattern");
            throw new NumberFormatException();
        } else {
            //Add a dot back in

            if (str.length() <= 2) {
                StringBuilder first = new StringBuilder(str.substring(0, pos));
                first.append('.');
                String last = str.substring(pos);
                str = first + last;
            } else {
                StringBuilder first = new StringBuilder(str.substring(0, str.length() - 2));
                first.append('.');
                String last = str.substring(str.length() - 2);

                str = first + last;
            }
        }
    }

    LOGGER.debug("Normalised result: " + str);
    return str;`

如何简化这种格式、提高效率并正确处理不正确的输入?

应用的解决方案

    String str = price;
    DecimalFormatSymbols dfsDot = new DecimalFormatSymbols();
    dfsDot.setDecimalSeparator('.');
    DecimalFormatSymbols dfsComma = new DecimalFormatSymbols();
    dfsComma.setDecimalSeparator(',');

    DecimalFormat dfDot = new DecimalFormat("#,##0.00", dfsDot);
    DecimalFormat dfComma = new DecimalFormat("#,##0.00", dfsComma);

    double d = 0;
    try {
        if (!str.contains(",") && !str.contains(".")) {
            return str;
        } else if (str.contains(",")) d = (Double) dfComma.parse(str);
        else if (str.contains(".")) d = (Double) dfDot.parse(str);
        str = "" + d;
    } catch (ParseException e) {
        LOGGER.debug(str + " couldn't be cast to Double");
        e.printStackTrace();
        return price;
    }

最佳答案

你知道DecimalFormat吗?

DecimalFormatSymbols dfs =new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
DecimalFormat df = new DecimalFormat("#,##0.00",dfs);
double d = df.parse("123.45").doubleValue();
System.out.println(d);

它打印:

123.45

关于java - 如何正确格式化数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39095988/

相关文章:

string - 如何将 char 转换为 String?

mysql - 在MySQL中使用子字符串从字符串中过滤特定的单词

java - JPA:在单个持久性单元上映射多个 Oracle 用户

java - 使用 nio 在 java 中实现非阻塞客户端服务器聊天应用程序

java - 如何获取所有实现指定接口(interface)的类

Java在while循环中对局部变量进行子字符串化

java - 避免正面比较的“占位符”字符?

string - 在 ByteString 上拆分 ByteString(而不是 Word8 或 Char)

java - 编译或运行时出现 java 错误

java - 如何在运行时更改 log4j2 的配置文件?