Convert a number to 2 decimal places in Java

前端 未结 4 1788
孤街浪徒
孤街浪徒 2020-12-01 15:31

I want to convert a number to a 2 decimal places (Always show two decimal places) in runtime. I tried some code but it only does, as shown below

 20.03034 &g         


        
相关标签:
4条回答
  • 2020-12-01 16:25

    Try this: String.format("%.2f", angle);

    0 讨论(0)
  • 2020-12-01 16:27

    try this new DecimalFormat("#.00");

    update:

        double angle = 20.3034;
    
        DecimalFormat df = new DecimalFormat("#.00");
        String angleFormated = df.format(angle);
        System.out.println(angleFormated); //output 20.30
    

    Your code wasn't using the decimalformat correctly

    The 0 in the pattern means an obligatory digit, the # means optional digit.

    update 2: check bellow answer

    If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27

    0 讨论(0)
  • 2020-12-01 16:33

    Try

    DecimalFormat df = new DecimalFormat("#,##0.00");
    
    0 讨论(0)
  • 2020-12-01 16:37
    DecimalFormat df=new DecimalFormat("0.00");
    

    Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.

    Instead if you use:

    DecimalFormat df=new DecimalFormat("#.00");  
    

    It wont convert 0.2659 into 0.27. You will get an answer like .27.

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