Java: double: how to ALWAYS show two decimal digits

后端 未结 6 1969
悲&欢浪女
悲&欢浪女 2021-02-03 23:23

I use double values in my project and I would like to always show the first two decimal digits, even if them are zeros. I use this function for rounding and if the value I print

6条回答
  •  孤街浪徒
    2021-02-03 23:48

    You can use something like this:

    If you want to retain 0 also in the answer: then use (0.00) in the format String

    double d = 2.46327;
    DecimalFormat df = new DecimalFormat("0.00");
    System.out.print(df.format(d));
    

    The output: 2.46

    double d = 0.0001;
    DecimalFormat df = new DecimalFormat("0.00");
    System.out.print(df.format(d));
    

    The output: 0.00

    However, if you use DecimalFormat df = new DecimalFormat("0.##");

    double d = 2.46327;
    DecimalFormat df = new DecimalFormat("0.##");
    System.out.print(df.format(d));
    

    The output: 2.46

    double d = 0.0001;
    DecimalFormat df = new DecimalFormat("0.##");
    System.out.print(df.format(d));
    

    The output: 0

提交回复
热议问题