printf如何使用前导零进行浮点运算

时间:2010-07-09 11:51:21

标签: java php c perl printf

我知道如何做X量的前导零,我知道如何做X小数点。但是,我该怎么做呢?

我希望有4个前导零到小数精度2:0000.00。 因此43.4将是0043.40

3 个答案:

答案 0 :(得分:19)

试试这个printfCPerlPHP)格式字符串:

"%07.2f"

答案 1 :(得分:8)

以下是您需要的代码:

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

答案 2 :(得分:-1)

Java:使用Formatter类。预期用法示例:

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)"