How to use DecimalFormat?

Posted in /  

How to use DecimalFormat?

    NumberFormat classes, including DecimalFormat, are packaged in the java.text package in Java. These are used to print information in a particular format. It is useful to format the numbers to print currencies or long values that can be otherwise confusing.

    How to use Java DecimalFormat

    In a simple example below, we have defined a number, which we will print without and with formatting, so that you can see the difference:

    NumberFormat nfm = new DecimalFormat("#,#,###.000");
    double amount = 134563232.67;
    System.out.println("Without formatting: " + amount);
    System.out.println("With formatting: " + nfm.format(amount));

    The output will be:

    Without formatting: 1.3456323267E8
    With formatting: 134,563,232.670

    Note that the second number is more readable. The method format can be applied to long and float as well:

    nfm = new DecimalFormat("##,###.00");
    System.out.println("Without formatting: " + (float)1111.232);
    System.out.println("With formatting: " +  nfm.format((float)1111.232));

    Setting group size will change the grouping of integers in the parts:

    nfm.setGroupingSize(4);
    System.out.println(nfm.format(amount));

    This will create groups of 4 instead of 3: 1,3456,3232.67 We can also get the currency of a particular Locale and print that:

    nfm = new DecimalFormat("¤##,###.00");
    nfm.setCurrency(Currency.getInstance(Locale.ITALY));
    System.out.println(nfm.getCurrency());
    System.out.println("With formatting: " + nfm.format(amount));

    The output will be: “With formatting: EUR134,563,232.67”. You can get and print the symbol of the currency using the getSymbol() method:

    nfm.getCurrency().getSymbol(Locale.ITALY);

    To print the resulting amount with the symbol, you should set the NumberFormat object (nfm) accordingly:

    nfm = DecimalFormat.getCurrencyInstance(Locale.ITALY);
    System.out.println("With symbol: " + nfm.format(amount));

    Conclusion

    We have seen how to use DecimalFormat to print an amount in any format that we want. We can also get the currency of a particular locale and prefix it on the number that we are formatting. For more methods and formats, check the Java documents for DecimalFormat .

    People are also reading:

    Ramya
    Written by

    Ramya Shankar

    A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.