Double decimal formatting in Java

后端 未结 14 1254
囚心锁ツ
囚心锁ツ 2020-11-22 05:17

I\'m having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it\'s 4.00 instead?

14条回答
  •  悲&欢浪女
    2020-11-22 06:00

    An alternative method is use the setMinimumFractionDigits method from the NumberFormat class.

    Here you basically specify how many numbers you want to appear after the decimal point.

    So an input of 4.0 would produce 4.00, assuming your specified amount was 2.

    But, if your Double input contains more than the amount specified, it will take the minimum amount specified, then add one more digit rounded up/down

    For example, 4.15465454 with a minimum amount of 2 specified will produce 4.155

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(2);
    Double myVal = 4.15465454;
    System.out.println(nf.format(myVal));
    

    Try it online

提交回复
热议问题