Double decimal formatting in Java

后端 未结 14 1222
囚心锁ツ
囚心锁ツ 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 05:57

    I know that this is an old topic, but If you really like to have the period instead of the comma, just save your result as X,00 into a String and then just simply change it for a period so you get the X.00

    The simplest way is just to use replace.

    String var = "X,00";
    String newVar = var.replace(",",".");
    

    The output will be the X.00 you wanted. Also to make it easy you can do it all at one and save it into a double variable:

    Double var = Double.parseDouble(("X,00").replace(",",".");
    

    I know that this reply is not useful right now but maybe someone that checks this forum will be looking for a quick solution like this.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题