0

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>
macemers
  • 2,194
  • 6
  • 38
  • 55

2 Answers2

0

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.

Stephen Buttolph
  • 643
  • 8
  • 16
  • I understand that it's a general way. But in may case, I need to pass `person` object to `xstream` for xml convertion and the `person` object hold a field with double type. When formatted, it becomes `String` – macemers Apr 03 '14 at 03:32
0

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);
dronidze
  • 86
  • 1
  • 3
  • It's the solution. BTW `xstream` call `toString(Object obj)` method to convert object to xml? – macemers Apr 03 '14 at 07:13
  • Yes. All SingleValueConverters have to override toString to represent single value object. For more complex objects you can look at com.thoughtworks.xstream.converters.Converter (these kinds of converters might be registered with the same way). – dronidze Apr 03 '14 at 08:03