Search code examples
javaspringspring-bootbigdecimal

Java BigDecmal change negative value to positive


A third-party service sends a negative value to the BigDecimal field in my service. I need to make it positive.

I re-read tons of information on BigDecimal in Spring, but couldn't find how to fix this. I don’t know if this can be done with the help of annotation that will automatically change the sign from negative to positive, or do I need to manually change the sign?

For example, my DTO:

private BigDecimal priceValue;

The value -14.50 always comes to me, and I want the result to be 14.50 with a "+" sign.

I read in the documentation that @Positive can be used - but this doesn't work for me.


Solution

  • I would say absolute value is your friend here:

    https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#abs()

    just keep in mind that BigDecimal objects are immutable...

    public foo() 
    { 
        BigDecimal num = new BigDecimal("-14.51"); 
        System.out.println("Absolute value is " + num.abs()); 
    }