Question

I have one problem in BigDecimal with handling negative value in reverse order. I got a NumberFormatException. How can I solve it?

This is my code:

import java.math.BigDecimal;

public class Java_bigdecimal_signum {
    public static void main(String args[]) {

        BigDecimal obj = new BigDecimal("20.15-");
        int i = obj.signum();
        System.out.println("\nobject value : " + obj
                         + "\nmethod generated value : " + i);
    }
}

Exception is:

Exception in thread "main" java.lang.NumberFormatException
at java.math.BigDecimal.<init>(Unknown Source)
at java.math.BigDecimal.<init>(Unknown Source)
at Java_bigdecimal_signum.main(Java_bigdecimal_signum.java:6)

I need output below:

object value : -20.15
method generated value : -1

Thanks in Advance.

Était-ce utile?

La solution

Well, I am assuming that your getting your number String with the minus on the end from somewhere else in your actual code, rather than passing a String literal to BigDecimal. If so, you can just process the String variable before passing it to BigDecimal, and move the - from the end to the beginning like so.

import java.math.BigDecimal;

public class Java_bigdecimal_signum {
    public static void main(String args[]) {
        String number = "20.15-";
        if(number.endsWith("-")){ 
            number = "-" + number.substring(0, number.length() -1); 
        }
        BigDecimal obj = new BigDecimal(number);
        int i = obj.signum();
        System.out.println("\nobject value : " + obj
                     + "\nmethod generated value : " + i);
    }
}

And, to state the obvious, If you really are just passing a String literal to BigDecimal as in your example code, then just put the minus on the beginning. :)

Hope this helps.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top