JAvaでdoubleタイプを文字列に変換して自動的に科学カウント法にフォーマットする
doubleタイプを使用する場合、doubleをStringに変換するにはString.valueOf(Double d)メソッドがよく使用されますが、String.valueOf(Double)はDouble自体のtoString()メソッドを呼び出します.
Double独自のtoStringメソッドでは、FloatingDecimalを使用して数値をフォーマットします.コードは次のとおりです.
このメソッドのコメントには、次のように書かれています.
数字が10より大きい7次または10より小さい-3次であれば,科学的カウント法が用いられることが明らかになった.これは多くの場合に適用されますが、多くの場所で頭が痛いです.この問題を回避するには、自分でフォーマットクラスを使用して再フォーマットする必要があります.最も簡単なのはDecimalFormatクラスを用いてフォーマットし,これを用いて科学カウント法に変換されない文字列を容易に得ることができる.
これでいいの~
/**
* 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);
これでいいの~