Show padding zeros using DecimalFormat
Asked Answered
M

8

38

I'm using DecimalFormat to format doubles to 2 decimal places like this:

DecimalFormat dec = new DecimalFormat("#.##");
double rawPercent = ( (double)(count.getCount().intValue()) / 
                            (double)(total.intValue()) ) * 100.00;
double percentage = Double.valueOf(dec.format(rawPercent));

It works, but if i have a number like 20, it gives me this:

20.0

and I want this:

20.00

Any suggestions?

Mavismavra answered 16/11, 2009 at 2:27 Comment(0)
T
40

The DecimalFormat class is for transforming a decimal numeric value into a String. In your example, you are taking the String that comes from the format( ) method and putting it back into a double variable. If you are then outputting that double variable you would not see the formatted string. See the code example below and its output:

int count = 10;
int total = 20;
DecimalFormat dec = new DecimalFormat("#.00");
double rawPercent = ( (double)(count) / (double)(total) ) * 100.00;

double percentage = Double.valueOf(dec.format(rawPercent));

System.out.println("DF Version: " + dec.format(rawPercent));
System.out.println("double version: " + percentage);

Which outputs:

"DF Version: 50.00"
"double version: 50.0"
Touristy answered 16/11, 2009 at 2:51 Comment(0)
F
20

Try this code:

BigDecimal decimal = new BigDecimal("100.25");

BigDecimal decimal2 = new BigDecimal("1000.70");

BigDecimal decimal3 = new BigDecimal("10000.00");

DecimalFormat format = new DecimalFormat("###,###,###,###,###.##");

format.setDecimalSeparatorAlwaysShown(true);

format.setMinimumFractionDigits(2);

System.out.println(format.format(decimal));

System.out.println(format.format(decimal2));

System.out.println(format.format(decimal3));

Result:

100.25

1,000.70

10,000.00
Funicular answered 2/4, 2014 at 18:56 Comment(2)
How does your answer add anything to the question? The question has been answered 4 years ago and apparently to the satisfaction of the OP. Also: please use the provided formatting facilities to format your code.Asci
This answer helped me, as I used format.setMinimumFractionDigits(). While not the same as the OP's case, in my case, I needed to change the number of decimal places depending on other factors, so this allowed me to keep a single overall pattern, but vary the number of decimal places.Metaplasm
J
8

You can try something like:

DecimalFormat df = new DecimalFormat("0.000000");
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(2);

This way you can ensure the minimum number of digits before or after the decimal

Jaymie answered 16/11, 2009 at 7:17 Comment(0)
D
7

Use format "#.00".

Decato answered 16/11, 2009 at 2:37 Comment(2)
You haven't showed us your print statement. If you do dec.format(percentage), the format will work.Decato
It is better to use "0.00" as "#.00" would format 0 as .00 which doesn't look good in my opinion.Gironde
A
6

I found my small test program useful and want to share it with you. Enjoy.

package be.softwarelab.numbers;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

public class DecimalNumbers {

    private static final double ZERO = 0;
    private static final double TEN = 10.0;
    private static final double PI = Math.PI;                           // 3.141592653589793;
    private static final double MILLIONS = Math.E * Math.pow(10, 6);    // 2718281.828459045;
    private static final double NINERS = 9999999.99999;

    public static void main(String[] args) {

        String format01 = "#.#";
        String format02 = "0.#";
        String format03 = "#.0";
        String format04 = "0.0";
        String format05 = "##.#";
        String format06 = "00.#";

        String formatAll = "###,###.###";
        String formatLong = "#.#########";  

        System.out.println("====== ZERO =================================================");
        showResult(ZERO, format01, Locale.US);
        showResult(ZERO, format02, Locale.US);
        showResult(ZERO, format03, Locale.US);
        showResult(ZERO, format04, Locale.US);
        showResult(ZERO, format05, Locale.US);
        showResult(ZERO, format06, Locale.US);
        System.out.println("====== TEN  =================================================");
        showResult(TEN, format01, Locale.US);
        showResult(TEN, format02, Locale.US);
        showResult(TEN, format03, Locale.US);
        showResult(TEN, format04, Locale.US);
        showResult(TEN, format05, Locale.US);
        showResult(TEN, format06, Locale.US);
        System.out.println("====== PI   =================================================");
        showResult(PI, format01, Locale.US);
        showResult(PI, format02, Locale.US);
        showResult(PI, format03, Locale.US);
        showResult(PI, format04, Locale.US);
        showResult(PI, format05, Locale.US);
        showResult(PI, format06, Locale.US);
        System.out.println("====== MILLIONS =============================================");
        showResult(MILLIONS, formatAll, Locale.US);
        showResult(MILLIONS, formatAll, Locale.GERMANY);
        showResult(MILLIONS, formatAll, Locale.FRANCE);
        showResult(MILLIONS, formatAll, new Locale("nl", "BE"));
        System.out.println("====== NINERS   =============================================");
        showResult(NINERS, format01, Locale.US);
        showResult(NINERS, format02, Locale.US);
        showResult(NINERS, format03, Locale.US);
        showResult(NINERS, format04, Locale.US);
        showResult(NINERS, format05, Locale.US);
        showResult(NINERS, format06, Locale.US);
        showResult(NINERS, formatLong, Locale.US);
        System.out.println("=============================================================");
    }

    public static void showResult(double number, String format, Locale locale) {
        // Using a Locale to see the differences between regions.
        DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(locale);
        DecimalFormat formatter = new DecimalFormat (format, otherSymbols);

        // Create the String result
        String output = formatter.format(number);

        // Format the output for a nice presentation.
        System.out.format("    %s %20s %11s = %20s\n", locale, number, format, output);
    }
}

This results in:

====== ZERO =================================================
en_US                  0.0         #.# =                    0
en_US                  0.0         0.# =                    0
en_US                  0.0         #.0 =                   .0
en_US                  0.0         0.0 =                  0.0
en_US                  0.0        ##.# =                    0
en_US                  0.0        00.# =                   00
====== TEN  =================================================
en_US                 10.0         #.# =                   10
en_US                 10.0         0.# =                   10
en_US                 10.0         #.0 =                 10.0
en_US                 10.0         0.0 =                 10.0
en_US                 10.0        ##.# =                   10
en_US                 10.0        00.# =                   10
====== PI   =================================================
en_US    3.141592653589793         #.# =                  3.1
en_US    3.141592653589793         0.# =                  3.1
en_US    3.141592653589793         #.0 =                  3.1
en_US    3.141592653589793         0.0 =                  3.1
en_US    3.141592653589793        ##.# =                  3.1
en_US    3.141592653589793        00.# =                 03.1
====== MILLIONS =============================================
en_US    2718281.828459045 ###,###.### =        2,718,281.828
de_DE    2718281.828459045 ###,###.### =        2.718.281,828
fr_FR    2718281.828459045 ###,###.### =        2 718 281,828
nl_BE    2718281.828459045 ###,###.### =        2.718.281,828
====== NINERS   =============================================
en_US        9999999.99999         #.# =             10000000
en_US        9999999.99999         0.# =             10000000
en_US        9999999.99999         #.0 =           10000000.0
en_US        9999999.99999         0.0 =           10000000.0
en_US        9999999.99999        ##.# =             10000000
en_US        9999999.99999        00.# =             10000000
en_US        9999999.99999 #.######### =        9999999.99999
=============================================================
Abridgment answered 26/10, 2016 at 11:32 Comment(0)
A
5

Try this code:

int count = 10;
int total = 20;
int another=0;
DecimalFormat df = new DecimalFormat("0.00");

System.out.println(df.format(count));
System.out.println(df.format(total ));
System.out.println(df.format(another));

The output is: 10.00 20.00 0.00

Aubree answered 13/3, 2013 at 9:4 Comment(0)
W
0

Try using a DecimalFormat of "0.00" instead. According to the JavaDocs, this won't strip off the extra 0s.

Wolsky answered 16/11, 2009 at 2:38 Comment(1)
it's still stripping off an extra zero with the "0.00" format :(Mavismavra
A
0

Just change

DecimalFormat dec = new DecimalFormat("#.##");

with

DecimalFormat dec = new DecimalFormat("#.00");
Ameba answered 7/9, 2020 at 22:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.