Search code examples
javaxmlxstreamscientific-notation

How to avoid scientific notation of a large double while converting to xml with xstream in Java


I'm using xstream to convert a object in xml format while the class has a double field.

Recently I found a object with a large double like 140936219.00

But in the output xml file, it became:

<Person>
    <name>Mike</name>
    <amount>1.40936219E8</amount>
    <currency>USD</currency>
    <currencyAmount>1.40936219E8</currencyAmount>
</Person>

The codes in Java like this:

XStream xstream = new XStream(new DomDriver());
xstream.alias("Person", PersonBean.class);
return xstream.toXML(person);

May I ask how to avoid the scientific notation in this case? Basically what I want is :

<Person>
    <name>Mike</name>
    <amount>140936219.00</amount>
    <currency>USD</currency>
    <currencyAmount>140936219.00</currencyAmount>
</Person>

Solution

  • You can define your own converter. For example

    import com.thoughtworks.xstream.converters.basic.DoubleConverter;
    
    public class MyDoubleConverter extends DoubleConverter
    {
        @Override
        public String toString(Object obj)
        {
            return (obj == null ? null : YourFormatter.format(obj));
        }
    }
    

    and then register it in a XStream object with high priority

    XStream xstream = new XStream(new DomDriver());
    xstream.alias("Person", PersonBean.class);
    xstream.registerConverter(new MyDoubleConverter(), XStream.PRIORITY_VERY_HIGH);
    return xstream.toXML(person);