Javaの小数点以下2桁にdouble/float値を丸める方法
私が知っているように、2つの方法で小数点以下を2つに丸めることができます:
-
Math.round(double
100.0)/100.0** -
DecimalFormat( ”
#.
“)
-
倍** 100.0 – 120563.18
-
Math.round(double ** 100.0) – 120563.00(最も近い値に丸める)
-
Math.round(double ** 100.0)/100.0~1205.63
-
ケース2:ダブル= 1205.6358 **
-
-
倍** 100.0 – 120563.58
-
Math.round(double ** 100.0) – 120564.00(最も近い値に丸める)
-
Math.round(double ** 100.0)/100.0~1205.64
どちらも同じ結果になっていますが、新しいカスタムコードを作成する理由は何ですか?Javaビルドイン
DecimalFormatクラスが常に推奨されます
。
例
-
Math.round
と
DecimalFormat ** クラスを使用して小数点以下2桁を丸めるJavaの例。
package com.mkyong; import java.text.DecimalFormat; public class RoundValue { public static void main(String[]args) { double kilobytes = 1205.6358; System.out.println("kilobytes : " + kilobytes); double newKB = Math.round(kilobytes** 100.0)/100.0; System.out.println("kilobytes (Math.round) : " + newKB); DecimalFormat df = new DecimalFormat("###.##"); System.out.println("kilobytes (DecimalFormat) : " + df.format(kilobytes)); } }
結果
kilobytes : 1205.6358 kilobytes (Math.round) : 1205.64 kilobytes (DecimalFormat) : 1205.64