How to print a double value with zero in java?

Asked

Viewed 98 times

1

I would like to print a double array value in Java, example:

  • 8,00 <- I’d like the exit to be 08,00.

How can I do that?

public class Main
{
    public static void main(String[] args) {
        
        double[] exemplo = {24.00, 8.00, 16.00, 14.00, 10.00};
        
        for (int l = 0; l < 5; l++){

            System.out.printf("%.2f \t| \n", exemplo[l]);
        }
        
    }
}

2 answers

3


One way to solve the problem is by using the class NumberFormat.

NumberFormat is the abstract base class for all number formats. This class provides a standard way to format and parse numbers.

This class also provides methods to determine which localities have certain number formatting patterns and which names of those localities.

In this way as you want to format a decimal number, we should use the concrete class DecimalFormat which is a subclass of NumberFormat.

When reviewing class documentation DecimalFormat we see that there is a special character pattern that we must "assemble" to generate the desired number formatting. These special characters must be passed in the constructor of the class DecimalFormat.

Symbol Type Meaning
0 number Digit
# number Digit, omit the zero
. number Decimal separator

*I am only representing the values I used in the answer, for more options see the class javadoc DecimalFormat.

Follow an example:

 double[] exemplo = {24.00, 8.00, 16.00, 14.00, 10.00};
 NumberFormat nf = new DecimalFormat("00.00");
 for (int l = 0; l < 5; l++){
     System.out.println(nf.format(exemplo[l]));
 }

So must have the expected result.

If you want it is also possible to "format" the decimal separator (swap semicolon for example), for this you will need to use the class DecimalFormatSymbols

This class represents the set of symbols (such as the decimal separator, the grouping separator and so on) required in the class DecimalFormat to format numbers.

An interesting use case would be to customize a formatting.

Follow an example:

 DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.getDefault());
 dfs.setDecimalSeparator(',');

 double[] exemplo = {24.00, 8.00, 16.00, 14.00, 10.00};
 NumberFormat  nf = new DecimalFormat("00.00", dfs);
 for (int l = 0; l < 5; l++){
     System.out.println(nf.format(exemplo[l]));
 }

In the above example it would be simpler to use a locale that already has a comma as a decimal separator.

DecimalFormatSymbols dfs = new DecimalFormatSymbols(new Locale("pt", "BR"));

This way you do not depend on the default locale (which can even be changed by any application running in the same JVM (since this is a shared resource), that is, it is something you do not control). Besides, if the default locale is some other, it may have other different settings, like the thousands separator (it’s okay that in this case it’s not being used, but it’s better to already use the correct locale than to use the default and quit changing everything)

A list of locales that the Java language has support can be seen here.

It is also possible to format monetary values using the currency, follow an example:

NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
nf.setMinimumIntegerDigits(2);
System.out.println(nf.format(24.00));
//R$ 24,00

This way it will already format as currency ( which already includes the "R$"). Changing the locales will also change the presentation.

  • 1

    The simplest is to use one locale that already has the comma as decimal separator: new DecimalFormatSymbols(new Locale("pt", "BR")) - so you don’t stay depending on the default locale (that can even be changed by any application running on the same JVM, that is, it is something that you do not control). Even because, if the default locale for some other, it may have other different settings, such as the thousands separator (all right that in this case is not being used, but it is better to already use the locale correct than using the default and go on changing everything)

  • 1

    Another option is to create the formatter with the correct locale (it is "ugly" but anyway): NumberFormat nf = NumberFormat.getNumberInstance(new Locale("pt", "BR")); ((DecimalFormat) nf).applyPattern("00.00"); - without it, falls into the same problem: it will use the decimal separator of the default locale, that may not always be right (do Locale.setDefault(Locale.US); at the beginning of the program and see that now it uses the point and not the comma). Finally, if it is to show the "R$", you can use nf = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")); nf.setMinimumIntegerDigits(2); which already includes "R$"

  • @hkotsubo I will add these caveats in the answer, have problem?

  • 1

    No problem, can add :-)

3

Use the method:

public PrintStream format​(String format, Object... args)

The method PrintStream.format() writes a formatted string in stream output using as parameters:

  • format- A format string, as described in Syntax of the format string.
  • args- Arguments referenced by format specifiers in the format string.
class Main {
  public static void main(String[] args) {
     double[] exemplo = {24.00, 8.00, 16.00, 14.00, 10.00};
        
     for (int l = 0; l < 5; l++){
        System.out.format("%05.2f \t| \n", exemplo[l]);
     }
  }
}

Exit:

24.00   | 
08.00   | 
16.00   | 
14.00   | 
10.00   | 

Test the code on Repl.it

In the case of the format specifier %05.2f means:

  • 05 - At least five characters will be printed and the missing characters will be completed with left zeros.
  • .2 - The value will be restricted to two decimal places.
  • f - The result will be formatted as decimal number.
  • 1

    It is worth remembering that the decimal separator will be the default locale which is configured in the JVM, which cannot always be the comma. If you want to force a specific separator, you can pass the locale for format, thus: System.out.format(new Locale("pt", "BR"), "%05.2f \t| \n", exemplo[l])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.