How to use Java's DecimalFormat for “smart” currency formatting?

前端 未结 10 615
旧巷少年郎
旧巷少年郎 2021-01-01 09:34

I\'d like to use Java\'s DecimalFormat to format doubles like so:

#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41

Th

10条回答
  •  长发绾君心
    2021-01-01 10:30

    You can check "is number whole or not" and choose needed number format.

    public class test {
    
      public static void main(String[] args){
        System.out.println(function(100d));
        System.out.println(function(100.5d));
        System.out.println(function(100.42d));
      }
    
      public static String function(Double doubleValue){
        boolean isWholeNumber=(doubleValue == Math.round(doubleValue));
        DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.GERMAN);
        formatSymbols.setDecimalSeparator('.');
    
        String pattern= isWholeNumber ? "#.##" : "#.00";    
        DecimalFormat df = new DecimalFormat(pattern, formatSymbols);
        return df.format(doubleValue);
      }
    }
    

    will give exactly what you want:

    100
    100.50
    100.42
    

提交回复
热议问题