Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell jaxb to truncate a BigDecimal when marshalling to xml?

I have these two classes:

@XmlAccessorType(XmlAccessType.FIELD)
public class OpportunityLocation
{

    @XmlElement
    private LatitudeLongitude coordinates;
    [...]
}

public class LatitudeLongitude implements Serializable
{
    private BigDecimal latitude;
    private BigDecimal longitude;
    [...]
}

when OpportunityLocation is serialized I get

<location>
    [...]
    <coordinates>
    <latitude>51.53684899999999657893567928113043308258056640625</latitude>
    <longitude>-0.1325880000000000114024345521102077327668666839599609375</longitude>
    </coordinates>

Now I've been asked to provide an xsd to validate the xml, I set the type of latitude and longitude to xsd:decimal but the validator complains that

 Element 'latitude': '51.53684899999999657893567928113043308258056640625' is not a valid value of the atomic type 'xs:decimal'.

(same for longitude)

The xsd fragment describing the coordinates is

<xs:complexType name="latitudeLongitude">
    <xs:all>
        <xs:element name="latitude" type="xs:decimal"/>
        <xs:element name="longitude" type="xs:decimal"/>
    </xs:all>
</xs:complexType>

I think the best solution would be to truncate the lat/long values, as there is no point to have that much precision in the first place.

How do I instruct JAXB to do that?

like image 866
acorello Avatar asked Dec 06 '25 06:12

acorello


1 Answers

Or simply use BigDecimal.setScale(). No need for an XmlAdapter if applicable to your case.

BigDecimal bd = new BigDecimal((double) 1.2345);
bd = bd.setScale(2, RoundingMode.HALF_UP);
like image 80
Vincenzo Z Avatar answered Dec 09 '25 20:12

Vincenzo Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!