Java decimal formatting using String.format?

后端 未结 6 679
迷失自我
迷失自我 2020-11-27 03:24

I need to format a decimal value into a string where I always display at lease 2 decimals and at most 4.

So for example

\"34.49596\" would be \"34.4         


        
相关标签:
6条回答
  • 2020-11-27 03:54

    You want java.text.DecimalFormat.

    DecimalFormat df = new DecimalFormat("0.00##");
    String result = df.format(34.4959);
    
    0 讨论(0)
  • 2020-11-27 03:59

    java.text.NumberFormat is probably what you want.

    0 讨论(0)
  • 2020-11-27 04:13

    NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode() method. You can use it to control how rounding or truncation is applied during formatting.

    0 讨论(0)
  • 2020-11-27 04:14

    Yes you can do it with String.format:

    String result = String.format("%.2f", 10.0 / 3.0);
    // result:  "3.33"
    
    result = String.format("%.3f", 2.5);
    // result:  "2.500"
    
    0 讨论(0)
  • 2020-11-27 04:18

    You want java.text.DecimalFormat

    0 讨论(0)
  • 2020-11-27 04:19

    Here is a small code snippet that does the job:

    double a = 34.51234;
    
    NumberFormat df = DecimalFormat.getInstance();
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(4);
    df.setRoundingMode(RoundingMode.DOWN);
    
    System.out.println(df.format(a));
    
    0 讨论(0)
提交回复
热议问题