android parsing negative number strings

孤者浪人 提交于 2019-12-01 05:56:25

问题


How to parse negative number strings?

strings may be of the form:

-123.23  
(123.23)  
123.23-

is there a class that will convert any of the above strings to a number?

if not, what is the best way to do it?


回答1:


Building on WarrenFaiths answer you can add this:

Double newNumber = 0;
if(number.charAt(i).isDigit()){
     //parse numeber here using WarrenFaiths method and place the int or float or double 
     newNumber = Double.valueOf(number);
}else{
    Boolean negative = false;

    if(number.startsWith("-") || number.endsWith("-")){
         number = number.replace("-", "");
         negative = true;
    }
    if(number.startsWith("(") || number.endsWith(")"){
        number = number.replace("(", "");
        number = number.replace(")", "");
    }

    //parse numeber here using WarrenFaiths method and place the float or double 
    newNumber = Double.valueOf(number);

    if(negative){
      newNumber = newNumber * -1;
    }
}

Im sorry if the replace methods are wrong, please correct me.




回答2:


"-123.23" can be parsed with Float.valueOf("-123.23"); or Double.valueOf("-123.23");

"(123.23)" and "123.23-" are invalid and need to be improved/parsed by yourself. You could go through the string step by step and check if it is a number, if so add it to a new string. If you find a - at the beginning or the end, make it than negative...




回答3:


here's the hack, pls comment on improvements etc, time to learn some more myself :)

private Double RegNumber(String sIn) {
        Double result = 0E0;
        Pattern p = Pattern.compile("^\\-?([0-9]{0,3}(\\,?[0-9]{3})*(\\.?[0-9]*))");   // -1,123.11
        Matcher m = p.matcher(sIn);
        if (m.matches()) {
            result = Double.valueOf(sIn);
        } else {
            Pattern p1 = Pattern.compile("^\\(?([0-9]{0,3}(\\,?[0-9]{3})*(\\.?[0-9]*))\\)?$");  // (1,123.22)
            Matcher m1 = p1.matcher(sIn);
            if (m1.matches()) {
                String x[] = sIn.split("(\\({1})|(\\){1})"); // extract number
                result = Double.valueOf("-" + x[1]);
            } else {
                Pattern p2 = Pattern.compile("([0-9]{0,3}(\\,?[0-9]{3})*(\\.?[0-9]*))\\-$");  // 1,123.22-
                Matcher m2 = p2.matcher(sIn);
                if (m2.matches()) {
                    String x[] = sIn.split("(\\-{1})"); // extract number
                    result = Double.valueOf("-" + x[0]);
                } else {
                    result = 99999999E99;  // error, big value
                }
            }
        }
        return result;
    }


来源:https://stackoverflow.com/questions/10448712/android-parsing-negative-number-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!