java中double类型转换成字符串自动格式化成科学计数法

在使用double类型的时候,常常使用String.valueOf(Double d)方法来将double转换成String,而String.valueOf(Double)调用的是Double自身的toString()方法。
/**
* Returns the string representation of the <code>double</code> argument.
* <p>
* The representation is exactly the one returned by the
* <code>Double.toString</code> method of one argument.
*
* @param d a <code>double</code>.
* @return a string representation of the <code>double</code> argument.
* @see java.lang.Double#toString(double)
*/
public static String valueOf(double d) {
return Double.toString(d);
}

而Double自身的toString方法使用FloatingDecimal来对数字进行格式化,代码如下:
    public static String toString(double d) {
return new FloatingDecimal(d).toJavaFormatString();
}

该方法注释中写到:
  * <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or
* equal to 10<sup>7</sup>, then it is represented in so-called
* "computerized scientific notation." Let <i>n</i> be the unique
* integer such that 10<sup><i>n</i></sup> <= <i>m</i> <
* 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the
* mathematically exact quotient of <i>m</i> and
* 10<sup><i>n</i></sup> so that 1 <= <i>a</i> < 10. The
* magnitude is then represented as the integer part of <i>a</i>,
* as a single decimal digit, followed by '<code>.</code>'
* (<code>'\u002E'</code>), followed by decimal digits
* representing the fractional part of <i>a</i>, followed by the
* letter '<code>E</code>' (<code>'\u0045'</code>), followed
* by a representation of <i>n</i> as a decimal integer, as
* produced by the method {@link Integer#toString(int)}.

可以很明确的看到,如果数字大于10的7次方或者小于10的-3次方,就会使用科学计数法。这个在很多时候很适用,同时在很多地方也让很多人很头疼。想要避免这个问题,就要自己使用格式化类去重新格式化。最简单的使用DecimalFormat类去格式化,用这个可以很容易的得到不转换成科学计数法的字符串。
 DecimalFormat df = new DecimalFormat("###0.0#");//最多保留几位小数,就用几个#,最少位就用0来确定
String s=df.format(d);

这样就可以了~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值