我使用xstream
转换xml格式的对象,而该类有双字段。
最近我发现了一个像140936219.00
但是在输出xml文件中,它变成了:
<Person>
<name>Mike</name>
<amount>1.40936219E8</amount>
<currency>USD</currency>
<currencyAmount>1.40936219E8</currencyAmount>
</Person>
Java中的代码如下:
XStream xstream = new XStream(new DomDriver());
xstream.alias("Person", PersonBean.class);
return xstream.toXML(person);
请问在这种情况下如何避免使用科学记数法?基本上我想要的是:
<Person>
<name>Mike</name>
<amount>140936219.00</amount>
<currency>USD</currency>
<currencyAmount>140936219.00</currencyAmount>
</Person>
答案 0 :(得分:0)
您可以使用DecimalFormat类,例如:
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 :) )
现在,您可以使用大数字的String值执行任何操作,请注意String不是科学记数法。
答案 1 :(得分:0)
您可以定义自己的转换器。例如
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));
}
}
然后将其注册到具有高优先级的XStream对象
XStream xstream = new XStream(new DomDriver());
xstream.alias("Person", PersonBean.class);
xstream.registerConverter(new MyDoubleConverter(), XStream.PRIORITY_VERY_HIGH);
return xstream.toXML(person);