gpt4 book ai didi

java - 仅转换具有浮点值的字符串

转载 作者:行者123 更新时间:2023-12-01 13:47:55 24 4
gpt4 key购买 nike

我有一个名为 MyText.txt 的外部文本文件。我正在用 java 读取该文件并尝试仅提取浮点值。文本文件中的值和句子可能会有所不同。这是我到目前为止所拥有的:

MyFile.txt内容:

Harry have 21.00pounds. 11/25/2009 is my birthday.

我的代码是

for(int K = 1; K < myTextWords.length; K++){
String s = myTextWords[K];
try{
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException nfe){
System.err.println("NumberFormatException: " + nfe.getMessage());
}
}

问题是:

  1. 21.00 打印为

    float f = 21.0
  2. 11/25/2009 也转换为字符串并打印为

    float f = 11.0
    float f = 25.0
    float f = 2009.0

如何限制程序仅提取和转换类似于 21.00、190.20 的字符串。

**文本值的内容可能会有所不同,而不是固定的。

最佳答案

检查所有正则表达式模式

String decimalPattern = "([0-9]*)\\.([0-9]*)";  
String number="20.00";
boolean match = Pattern.matches(decimalPattern, number);
if(match){
try{
float f = Float.valueOf(number.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException nfe){
System.err.println("NumberFormatException: " + nfe.getMessage());
}
}

关于java - 仅转换具有浮点值的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20208626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com