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 a
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.
"-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...
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;
}