java - 如何从 Java 中的字符串格式数字中获取实际值?

标签 java string numbers

您能否建议从不同格式的字符串数字中检索实际值的最佳方法是什么?

示例:

我希望能够传递所有这些字符串:

101,00
101.00
-101,00
-101.00
100,000.00
100.000,00
-100,000.00
-100.000,00

并从方法中获取这些返回:

101.00
101.00
-101.00
-101.00
100000.00
100000.00
-100000.00
-100000.00

我应该使用 string.replaceAll("","") 还是有更好的方法?

谢谢

最佳答案

使用全部替换是行不通的。当您需要的是找到最后一次出现的“.”时或“,”并将其用作小数位。

基于http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

public static void main(String... args) throws ParseException {
    DecimalFormatSymbols dfs1 = new DecimalFormatSymbols();
    dfs1.setDecimalSeparator('.');
    dfs1.setGroupingSeparator(',');

    DecimalFormat df1 = new DecimalFormat("#,##0.00", dfs1);
    System.out.println(df1.format(-10000)+" parsed is "+df1.parse("-10,000.01"));

    DecimalFormatSymbols dfs2 = new DecimalFormatSymbols();
    dfs2.setDecimalSeparator(',');
    dfs2.setGroupingSeparator('.');

    DecimalFormat df2 = new DecimalFormat("#,##0.00", dfs2);
    System.out.println(df2.format(-10000)+" parsed is "+df2.parse("-10.000,01"));
}

打印

-10,000.00 parsed is -10000.01
-10.000,00 parsed is -10000.01

关于java - 如何从 Java 中的字符串格式数字中获取实际值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10346709/

相关文章:

assembly - 汇编器64b师

java - 正确使用 String lastIndexOf

java - 应为 BEGIN_ARRAY,但在第 1 行第 5 列为 STRING

Javascript 如果字符串中的字符出现次数相同

javascript - 两个相等的字符串表示 JS 中不相等的空格

bash - sed,只捕获数字

java - 在运行时配置 HikariCP + Hibernate + GuicePersist(JPA)

java - 当项目部署在 tomcat 上时 JDBC 数据源不工作

c - 读入一个字符串并比较它 C

string - 如何在 Bash 或 Unix shell 中检查字符串中的第一个字符?