How to properly display a price up to two decimals (cents) including trailing zeros in Java?

后端 未结 5 1438
小蘑菇
小蘑菇 2021-02-09 14:42

There is a good question on rounding decimals in Java here. But I was wondering how can I include the trailing zeros to display prices in my program like: $1.50, $1.00

T

相关标签:
5条回答
  • 2021-02-09 15:21

    While others answers are perfectly valid (especially duffymo's one), you have a much bigger problem than formatting the display. You are actually using a totally wrong type for a money amount which is a discrete value. Instead of a double, you should really consider using a java.lang.BigDecimal.

    (EDIT: ... or a well implemented Money class as duffymo pointed out in a comment, for example classes from JScience's monetary module or the more recent Joda-Money - which has still to be released as an official version.)

    0 讨论(0)
  • 2021-02-09 15:24
    public static String getFormattedData(String actualString) 
        {
            String subString = "0.0";
    
            if(actualString.contains("."))
            {   
                subString = actualString.substring(actualString.indexOf("."), actualString.trim().length()); 
    
                if(Double.parseDouble(subString) > 0.0)
                    return actualString;
                else
                    actualString = actualString.substring(0, actualString.indexOf("."));
            }
            return actualString;
        }
    
    0 讨论(0)
  • 2021-02-09 15:28

    I would recommend that you do this:

    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
    double price = 2.50000000000003;
    System.out.println(currencyFormatter.format(price));
    

    This has the virtue of be locale-specific as well. This will work, for example, if you're in the euro zone instead of the US.

    0 讨论(0)
  • 2021-02-09 15:28

    It can probably be done with String.format(...), but you could use DecimalFormat:

    double price = 2.50000000000003;
    DecimalFormat formatter = new DecimalFormat("$0.00");
    System.out.println(formatter.format(price)); // print: $2.50
    
    0 讨论(0)
  • 2021-02-09 15:46

    Have you tried:

    String s = String.format("$%.2f", 2.50);
    

    That will do the trick.

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