Strony

2018-06-12

Rounding BigDecimal into scale 2 in WebService

BigDecimalConverter class:
final class BigDecimalConverter {
    private final static Logger logger = LoggerFactory.getLogger(BigDecimalConverter.class);

    private static final int SCALE = 2;

    static String convertToString(BigDecimal bigDecimal) {
        if (bigDecimal == null) {
            return null;
        }

        logger.info("Rounding bigDecimal {} into scale {}", bigDecimal, SCALE);
        return bigDecimal.setScale(SCALE, RoundingMode.HALF_UP).toString();
    }
}
BigDecimalXmlAdapter class:
public class BigDecimalXmlAdapter extends XmlAdapter {
    private final static Logger logger = LoggerFactory.getLogger(BigDecimalXmlAdapter.class);

    @Override
    public BigDecimal unmarshal(String s) {
        logger.info("Unmarshal String: {}", s);

        try {
            return new BigDecimal(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public String marshal(BigDecimal bigDecimal) {
        logger.info("Marshal BigDecimal {}", bigDecimal);

        return BigDecimalConverter.convertToString(bigDecimal);
    }
}
package-info.java file:
@javax.xml.bind.annotation.XmlSchema(namespace = "http://app.host.pl/api/types", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters({
        @javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(value = pl.marceen.soap.control.BigDecimalXmlAdapter.class, type = java.math.BigDecimal.class)
})
package pl.host.app.api.types;