Question

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>
Was it helpful?

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);

OTHER TIPS

You could use the DecimalFormat class such as:

import java.text.DecimalFormat;
...
double yourBigNumber = 140936219.00;
DecimalFormat formater = new DecimalFormat("#.#"); //if you want to make it so it keeps the .00s
//then change the "#.#" to a "#.00".
String newNumber = formater.format(yourBigNumber);
System.out.println(newNumber); //Not needed ( if you couldn't tell :) )

Now you can do whatever you want with your String value of the big number, note the String is not in scientific notation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top