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

前端 未结 10 566
旧巷少年郎
旧巷少年郎 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:13

    Try using

    DecimalFormat.setMinimumFractionDigits(2);
    DecimalFormat.setMaximumFractionDigits(2);
    
    0 讨论(0)
  • 2021-01-01 10:13

    I know its too late. However following worked for me :

    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK);
    new DecimalFormat("\u00A4#######0.00",otherSymbols).format(totalSale);
    
     \u00A4 : acts as a placeholder for currency symbol
     #######0.00 : acts as a placeholder pattern for actual number with 2 decimal 
     places precision.   
    

    Hope this helps whoever reads this in future :)

    0 讨论(0)
  • 2021-01-01 10:15

    You can use the following format:

    DecimalFormat dformat = new DecimalFormat("$#.##");

    0 讨论(0)
  • 2021-01-01 10:20

    You can try by using two different DecimalFormat objects based on the condition as follows:

    double d=100;
    double d2=100.5;
    double d3=100.41;
    
    DecimalFormat df=new DecimalFormat("'$'0.00");
    
    if(d%1==0){ // this is to check a whole number
        DecimalFormat df2=new DecimalFormat("'$'");
        System.out.println(df2.format(d));
    }
    
    System.out.println(df.format(d2));
    System.out.println(df.format(d3));
    
    Output:-
    $100
    $100.50
    $100.41
    
    0 讨论(0)
  • 2021-01-01 10:25

    Try

    new DecimalFormat("'$'0.00");
    

    Edit:

    I Tried

    DecimalFormat d = new DecimalFormat("'$'0.00");
    
            System.out.println(d.format(100));
            System.out.println(d.format(100.5));
            System.out.println(d.format(100.41));
    

    and got

    $100.00
    $100.50
    $100.41
    
    0 讨论(0)
  • 2021-01-01 10:27

    Does it have to use DecimalFormat?

    If not, it looks like the following should work:

    String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
    //Handle the weird exception of formatting whole dollar amounts with no decimal
    currencyString = currencyString.replaceAll("\\.00", "");
    
    0 讨论(0)
提交回复
热议问题