私が知っているように、2つの方法で小数点以下を2つに丸めることができます:


  1. Math.round(double

    100.0)/100.0**


  2. DecimalFormat( ”

    #.

    “)

  3. 倍** 100.0 – 120563.18

  4. Math.round(double ** 100.0) – 120563.00(最も近い値に丸める)

  5. Math.round(double ** 100.0)/100.0~1205.63

    • ケース2:ダブル= 1205.6358 **

  6. 倍** 100.0 – 120563.58

  7. Math.round(double ** 100.0) – 120564.00(最も近い値に丸める)

  8. 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