Java 如何将格式化字符串转换为浮点?

Java 如何将格式化字符串转换为浮点?,java,number-formatting,string-conversion,Java,Number Formatting,String Conversion,我有一个字符串列表,如果模式匹配,我想将它们转换为float 以下是一些值和预期结果: 1000 -> 1000.0 1.000 -> 1000.0 1.000,000 -> 1000.0 -1.000,000 -> -1000.0 9,132 -> 9.132 1,000.00 -> invalid 30.10.2010 -> invalid 1,000.000,00 -> inv

我有一个字符串列表,如果模式匹配,我想将它们转换为float

以下是一些值和预期结果:

1000         -> 1000.0
1.000        -> 1000.0
1.000,000    -> 1000.0
-1.000,000   -> -1000.0
9,132        -> 9.132
1,000.00     -> invalid
30.10.2010   -> invalid
1,000.000,00 -> invalid
我尝试使用此代码检查一个数字是否有效,但该模式从未匹配:

Pattern pattern = Pattern.compile("#.###,###");
for(String s : list){
    Matcher m = pattern.matcher(s); 
    if(m.matches()){
         //convert
    }
}
除此之外,我还尝试使用以下代码:

 DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance();
 for(String s : list){
        try {
            Number num = df.parse(s);
            //..
        } catch (ParseException e) {

        } 
    }
这段代码的问题是,没有执行基于模式的验证。例如,像
2012/05/30
这样的日期转换为
2012


那么,我如何定义一个有效的模式,或者根据自己的需要配置
DecimalFormat

模式类与正则表达式一起工作。你可能想要这个:

Pattern pattern = Pattern.compile("-?\d\.\d{1,3}(,\d{1,3})?");

您可能希望根据您想要或不想要匹配的格式来调整这个正则表达式。

模式类与正则表达式一起工作。你可能想要这个:

Pattern pattern = Pattern.compile("-?\d\.\d{1,3}(,\d{1,3})?");
您可能想根据您想要或不想要匹配的格式来调整这个正则表达式。

试试看

System.out.println("1,000.000,00".matches("^[+-]?\\d+(\\.\\d{3})*(,\\d+)?"));
我不确定你的号码能否以+开头,所以加上它以防万一。也不知道0100000.000.0001234是否有效。如果没有,请说明原因并更正正则表达式。

尝试

System.out.println("1,000.000,00".matches("^[+-]?\\d+(\\.\\d{3})*(,\\d+)?"));

我不确定你的号码能否以+开头,所以加上它以防万一。也不知道0100000.000.0001234是否有效。如果没有,请说明原因并更正正则表达式。

如果模式是逗号,请尝试:

String[] splitted = string.split(",")
如果拆分的
大小>2
-->无效

如果
splitted.size==2&&splitted[1]。拆分(“.”>0
-->也无效

如果格式良好-->删除所有点,将逗号替换为点,将逗号后的字符串解析为int并连接各部分


这是一种非常简单的方法,但它可以工作…

如果模式是逗号,请尝试:

String[] splitted = string.split(",")
如果拆分的
大小>2
-->无效

如果
splitted.size==2&&splitted[1]。拆分(“.”>0
-->也无效

如果格式良好-->删除所有点,将逗号替换为点,将逗号后的字符串解析为int并连接各部分


这是一个非常简单的方法,但它是有效的…

我想这就是你想要的。评论应该对此作出解释

@Test
public void testAllValues() {
    testValue("1000", "1000");
    testValue("1.000,000", "1000");
    testValue("-1.000,000", "-1000");
    testValue("9,132", "9.132");
    testValue("1,000.00", null);
    testValue("30.10.2010", null);
    testValue("1,000.000,00", null);
}

private void testValue(String germanString, String usString) {
    BigDecimal germanDecimal = (BigDecimal) parse(germanString);
    if (usString != null) {
        BigDecimal usDecimal = new BigDecimal(usString);
        assertEquals("German " + germanString + " did not equal US " + usString, 0, germanDecimal.compareTo(usDecimal));
    } else {
        assertEquals("German " + germanString + " should not have been pareseable", null, germanDecimal);
    }
}

public BigDecimal parse(String s) {
    // Patch because parse doesn't enforce the number of digits between the
    // grouping character (dot).
    if (!Pattern.matches("[^.]*(\\.\\d{3})*[^.]*", s)) {
        return null;
    }

    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMANY);
    df.setParseBigDecimal(true);

    // Have to use the ParsePosition API or else it will silently stop
    // parsing even though some of the characters weren't part of the parsed
    // number.
    ParsePosition position = new ParsePosition(0);
    BigDecimal parsed = (BigDecimal) df.parse(s, position);

    // getErrorIndex() doesn't seem to accurately reflect errors, but
    // getIndex() does reflect how far we successfully parsed.
    if (position.getIndex() == s.length()) {
        return parsed;
    } else {
        return null;
    }
}

我想这就是你想要的。评论应该对此作出解释

@Test
public void testAllValues() {
    testValue("1000", "1000");
    testValue("1.000,000", "1000");
    testValue("-1.000,000", "-1000");
    testValue("9,132", "9.132");
    testValue("1,000.00", null);
    testValue("30.10.2010", null);
    testValue("1,000.000,00", null);
}

private void testValue(String germanString, String usString) {
    BigDecimal germanDecimal = (BigDecimal) parse(germanString);
    if (usString != null) {
        BigDecimal usDecimal = new BigDecimal(usString);
        assertEquals("German " + germanString + " did not equal US " + usString, 0, germanDecimal.compareTo(usDecimal));
    } else {
        assertEquals("German " + germanString + " should not have been pareseable", null, germanDecimal);
    }
}

public BigDecimal parse(String s) {
    // Patch because parse doesn't enforce the number of digits between the
    // grouping character (dot).
    if (!Pattern.matches("[^.]*(\\.\\d{3})*[^.]*", s)) {
        return null;
    }

    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMANY);
    df.setParseBigDecimal(true);

    // Have to use the ParsePosition API or else it will silently stop
    // parsing even though some of the characters weren't part of the parsed
    // number.
    ParsePosition position = new ParsePosition(0);
    BigDecimal parsed = (BigDecimal) df.parse(s, position);

    // getErrorIndex() doesn't seem to accurately reflect errors, but
    // getIndex() does reflect how far we successfully parsed.
    if (position.getIndex() == s.length()) {
        return parsed;
    } else {
        return null;
    }
}

严格地说,你提到的数字应该是无效的,但我不希望出现这样的数字。因此,目前它可以很好地过滤我的列表。使用正则表达式,我无法使用
DecimalFormat
转换字符串,因为如果我更改正则表达式,格式可能不再正确。那么,有没有一种方法可以基于regex将字符串转换为float呢?@Pedro我从来没有使用过
DecimalFormat
,所以我帮不了你。很抱歉如果有必要的话,我现在唯一能为你做的就是定制更多的正则表达式。严格来说,你提到的数字应该是无效的,但我不希望出现这样的数字。因此,目前它可以很好地过滤我的列表。使用正则表达式,我无法使用
DecimalFormat
转换字符串,因为如果我更改正则表达式,格式可能不再正确。那么,有没有一种方法可以基于regex将字符串转换为float呢?@Pedro我从来没有使用过
DecimalFormat
,所以我帮不了你。很抱歉如果有必要,我现在唯一能为您做的就是定制更多的正则表达式。