简体   繁体   English

如何解析字符串以从中获取双精度值

[英]How to parse string to get double value from it

Help me please for the next problem: 请帮助我解决下一个问题:

There is String pattern, assume it's public final static variable. 有字符串模式,假定它是公共的最终静态变量。 There is string where we search. 在搜索的地方有字符串。 There is class, simple wrapper to double 有上课,简单的包装加倍

public class Wrapper {

    private double value;

    public double getValue() {
        return value;
    }

    public Wrapper(double value) {
        this.value = value;
    }
}

I need method 我需要方法

public Wrapper parse(String s, int index)

which returns Wrapper's object if string at the index is double number with maximum 2 digits after decimal point(if there is decimal point at all) and right after number ends there is String pattern after it For example for strings 如果索引处的字符串是双精度数,并且小数点后最多有2位数字(如果完全有小数点),则返回Wrapper的对象。数字结束后,紧随其后的是字符串模式,例如字符串

String pattern = "money";
String search = "Giveme10.25moneyplease";

parse(search, 6) returns new Wrapper(10.25) parse(search,6)返回新的包装器(10.25)

In other cases (index less then zero, greater then length of the string, substring that starts from index isn't number at all or it's double number but it contains more then 2 digits after decimal point or there is no string pattern after number) method must return null 在其他情况下(索引小于零,大于字符串的长度,从索引开始的子字符串根本不是数字,或者是双精度数字,但小数点后包含多于2位数字,或者数字后没有字符串模式)方法必须返回null

And another method that differs only string pattern must be first and then double number with maximum 2 digits after decimal point and all other the same 而另一个仅区别于字符串模式的方法必须是第一个,然后是双精度数,小数点后最多2位,其他所有相同

String pattern = "money"
String s = "Ihavemoney10.50"

parse1(s, 5) returns new Wrapper(10.50) parse1(s,5)返回新的包装器(10.50)

You can use DecimalFormat along with ParsePosition like this 您可以像这样将DecimalFormatParsePosition一起使用

import java.text.DecimalFormat;
import java.text.ParsePosition;

public class TestP {

    public static void main(String[] args) {


        DecimalFormat decimalFormat = new DecimalFormat("00.##'money'");

        String search = "Giveme10.25moneyplease";

        int index = 6;
        //output 10.25
       Number number = decimalFormat.parse(search, new ParsePosition(index));

    if (number != null) {
        String s = number.toString();           
        if (s.contains(".") && s.length() > 5) {
            number = null;
        }
    }
    System.out.println(number);

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM