15

I know how to do X amount of leading zeros, and I know how to do X amount of decimal points. But how do I do them both?

I am looking to have 4 leading zeros with a decimal precision of 2: 0000.00. Therefore 43.4 would be 0043.40

0

3 Answers 3

23

Try this printf (C, Perl, PHP) format string:

"%07.2f"
3
  • java has a printf too... (System.out.printf() )
    – st0le
    Jul 11, 2010 at 12:08
  • @st0le: So does Python (via the % operator) but I didn't contribute the list of languages. Feel free to further edit the answer. Jul 12, 2010 at 1:55
  • 5
    It would be worthy to mention that first number (7) means total length that includes integer part, fractional part and the FP dot itself (and optional "minus" sign as well).
    – Konstantin
    Feb 14, 2016 at 15:46
9

Here is the code you need:

float myNumber = 43.4;
DecimalFormat formatter = new DecimalFormat("0000.00"); //use # for optional digits instead of 0
System.out.println(formatter.format(myNumber));
0
0

Java: use the Formatter class. Examples of expected usage:

StringBuilder sb = new StringBuilder();
// Send all output to the Appendable object sb
Formatter formatter = new Formatter(sb, Locale.US);

// Explicit argument indices may be used to re-order output.
formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
// -> " d  c  b  a"

// Optional locale as the first argument can be used to get
// locale-specific formatting of numbers.  The precision and width can be
// given to round and align the value.
formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);
// -> "e =    +2,7183"

// The '(' numeric flag may be used to format negative numbers with
// parentheses rather than a minus sign.  Group separators are
// automatically inserted.
formatter.format("Amount gained or lost since last statement: $ %(,.2f",
                balanceDelta);
// -> "Amount gained or lost since last statement: $ (6,217.58)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.