Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android parsing negative number strings

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?

like image 469
quiricada Avatar asked Apr 23 '26 11:04

quiricada


1 Answers

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.

like image 148
FabianCook Avatar answered Apr 25 '26 01:04

FabianCook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!