Formatting numbers using DecimalFormat

后端 未结 6 769
我寻月下人不归
我寻月下人不归 2021-01-01 21:05

I am trying to format prices using DecimalFormat, but this isn\'t working for all variations.

DecimalFormat df = new DecimalFormat(\"0.##\")
df.format(7.8)
d         


        
相关标签:
6条回答
  • 2021-01-01 21:35

    Use the BigDecimal number class instead:

    e.g. if n is a BigDecimal, then you can use

    String s = NumberFormat.getCurrencyInstance().format(n);
    

    By the way, it's best practice to use BigDecimal when working with money.

    0 讨论(0)
  • 2021-01-01 21:42

    I don't think it's possible, at least not with Java SE formatters. You need to make a custom formatter. I would do it like this

    String res = df.format(number).replace(".00", "");
    
    0 讨论(0)
  • 2021-01-01 21:47

    You can try with:

    DecimalFormat df = new DecimalFormat("#.##",new DecimalFormatSymbols(Locale.US));
    
    0 讨论(0)
  • 2021-01-01 21:53

    This doesn't seem to be solved by a single formatter. I suggest you use "0.00" format and replace ".00" with an empty string.

    public static String myFormat(double number) {
      DecimalFormat df = new DecimalFormat("0.00");
      return df.format(number).replaceAll("\\.00$", "");
    }
    
    0 讨论(0)
  • 2021-01-01 21:54
    System.out.println(new java.text.DecimalFormat("#.##").format(5.00));
    

    This will print 5

    System.out.println(new java.text.DecimalFormat("#.00").format(500.401));
    

    This will print 500.40

    0 讨论(0)
  • 2021-01-01 21:55

    There is a slight difference between these two formats. The "#.##" means it will print the number with maximum two decimal places whereas "#.00" means it will always display two decimal places and if the decimal places are less than two, it will replace them with zeros. see the example below with output.

    public static final DecimalFormat df1 = new DecimalFormat( "#.##" );
    public static final DecimalFormat df2 = new DecimalFormat( "#.00" );
    
    System.out.println(df1.format(7.80));
    System.out.println(df1.format(85));
    System.out.println(df1.format(85.786));
    
    System.out.println(df2.format(7.80));
    System.out.println(df2.format(85));
    System.out.println(df2.format(85.786));
    

    And the output will be

    7.8
    85
    85.79
    
    7.80
    85.00
    85.79
    
    0 讨论(0)
提交回复
热议问题