【问题标题】:printf how to do floating points with leading zerosprintf如何用前导零做浮点数
【发布时间】:2011-03-13 20:10:10
【问题描述】:

我知道如何处理 X 个前导零,并且我知道如何处理 X 个小数点。但是,我该怎么做呢?

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

【问题讨论】:

  • 请不要标记printf-question C++
  • @Space_C0wb0y:在 C++ 中使用 printf 没有任何问题。在理想世界中,每个人都会在他们的 C++ 中使用 iostream,但我们并不生活在理想世界中。此外,有时使用 printf 可以更轻松地按照自己想要的方式格式化字符串。
  • 在我看来,在 C++ 中使用 printf 确实有很大的错误。 C 和 C++ 是两种完全不同的语言,人们对 C++ 中哪些 C 特性可以使用,哪些不可以有不同的假设。不同的假设总是会导致麻烦。
  • 这种“C 和 C++ 是完全不同的语言”的东西会被重复太多... 一个问题:C++ 可以调用“普通”库吗? (“正常”,我的意思是,很可能,那里有大量很酷的“C”库......)答案是:是的。那么,为什么 C++ 应该“关闭”以仅调用用 C++ 制作的库?如果答案是:C++ 应该能够调用“普通 C 库”(例如:png lib、gsl 库……)4ever 不需要其适当的绑定(包括所有开销),那么为什么 C++ 不应该能够像任何其他没有特定 C++ 绑定的 func 库一样调用 std C 库中的 func 吗?
  • 哪些 C 特性在 C++ 中是可以的,哪些不是,几乎完全取决于一个人的意见。你不喜欢 printf?美好的。但是告诉人们他们不应该仅仅因为它在 C 标准库中或者因为你不喜欢它而使用它是愚蠢的。

标签: java php c perl printf


【解决方案1】:

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

"%07.2f"

【讨论】:

  • java 也有 printf... (System.out.printf() )
  • @st0le:Python 也是如此(通过% 运算符),但我没有提供语言列表。随意进一步编辑答案。
  • 值得一提的是,第一个数字 (7) 表示总长度,包括整数部分、小数部分和 FP 点本身(以及可选的“减号”符号)。
【解决方案2】:

这是您需要的代码:

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

【讨论】:

  • 顺便说一句,我现在正在使用其他一些编程语言进行编码。这就是我忘记在著名的 Java 编程约定中写变量 my_number 的名称:CamelCase。根据约定,它应该是 myNumber。 ;)
  • 请编辑您的答案,而不是评论解释“my_number”与myNumber。
  • 我认为他没有足够的代表来编辑他的答案。但我愿意。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    相关资源
    最近更新 更多