Jafar Ali
Jafar Ali

Reputation: 1114

How to parse a string number with negative sign at its back

We are consuming a service which returns a value as 20.000-. The trailing - signifies negative number. This is their standard.

How can I parse this to double without doing a string manipulation. I am looking for much direct way of parsing it.

Upvotes: 3

Views: 2594

Answers (4)

рüффп
рüффп

Reputation: 5448

Here is my solution by using also the Apache Common library (NumberUtils, useful for nullity check).

private Double normalizeDouble(String s){
    double multiple = 1.0D;
    if( s != null && s.endsWith("-")){
        multiple = -1.0D;
        s = s.replace("-", "");
    }

    return NumberUtils.toDouble(s) * multiple;
}

It is also compatible if numbers in the String are prefixed by the - character (normal behavior).

Upvotes: 0

Shar1er80
Shar1er80

Reputation: 9041

I see two things from this.

  1. String manipulation will have to be done
  2. Preserving the precision of the number, if you're number is like 0.00000 and you want to keep all the zeroes.

Having said that, give this a try:

public static void main(String[] args) throws Exception {
    String data = "20.123456-";

    // Determine if positive or negative
    boolean negative = data.charAt(data.length() - 1) == '-';
    double dblData = negative 
            ? Double.parseDouble(data.substring(0, data.length() - 1)) * -1
            : Double.parseDouble(data);

    // Determine precision
    long precision = 0;
    if (data.contains(".")) {
        String decimalPart = data.split("\\.")[1];
        // 0x30 and 0x39 are the hex values for characters 0 - 9
        precision = decimalPart.chars().filter(c -> 0x30 <= c && c <= 0x39).count();
    }
    NumberFormat nf = new DecimalFormat();
    nf.setMinimumFractionDigits((int)precision);

    // Display results
    System.out.println(nf.format(dblData));
}

Results:

-20.123456

Upvotes: 1

Rahul Chaudhary
Rahul Chaudhary

Reputation: 1061

This can be achieved in many ways-

1.above process is also aplicable

2.

String s = "200.0-";

    String[] str = s.split("-");

    double data=Double.parseDouble(str[0]);

    data*=-1;

Upvotes: 0

Pherion
Pherion

Reputation: 155

You'll have to manipulate the string so that you extract the negative sign first:

String number = "20.00-";
boolean negative = false;

if(number.substring(number.length() - 1).equals("-")) {
    number = number.substring(0, number.length() - 1);
    negative = true;
}

double parsedNumber = Double.parseDouble(number);

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

Upvotes: 2

Related Questions