如何使用 sprintf 控制 Perl 中的浮点格式?

发布于 2024-10-08 12:20:03 字数 556 浏览 0 评论 0原文

我通常使用%g,但似乎指数位数是系统-dependent,并且我无法像 %.4g%.2g 这样的变体工作(它们只是产生相同的结果,不是吗? )。

我实际上想做的是,如果数字(绝对值)在某个范围内(例如 10^5 > |x| > 10^-5),“在可能的情况下”使用简单的浮点表示,否则使用科学计数法。我还想将显示的位数限制为 5 位(这样我就不会得到像 0.12345678901234567890 这样的超大浮点数...)。

一些示例:

0.123456890 -> 0.12346

0.000000000123456 -> 1.23456e-10

我可以直接在 sprintf 中执行此操作还是必须编写一个特殊的包装器?

I usually use %g, but it seems the number of exponent digits is system-dependent, and I can't variants like %.4g or %.2g to work (they simply produce the same results, don't they?).

What I actually would like to do is to use simple floating point representation "when possible" if the number (in absolute value) is in some range (e.g. 10^5 > |x| > 10^-5), otherwise use scientific notation. I also want to limit the number of digits displayed to, say, 5 (so I won't get super huge floating point numbers like 0.12345678901234567890...).

Some examples:

0.123456890 -> 0.12346

0.000000000123456 -> 1.23456e-10

Can I do that directly in sprintf or do I have to write a special wrapper?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

朮生 2024-10-15 12:20:03

不,您必须编写一个自定义包装器才能获得您所描述的行为:作为 perlfunc 说:

对于“g”和“G”,[精度]指定
显示的最大位数,
包括小数点之前的
点及其后面的内容;

请注意,简单浮点表示中的前导零算作“数字”。

CPAN 上有一些模块可以帮助您编写类似 sprintf 的函数。 String::Sprintf 用于向常规 sprintf 格式。 String::Formatter 用于从头开始使用看起来像 sprintf 但不继承它的任何格式。

No, you'd have to write a custom wrapper to get the behavior you describe: As perlfunc says:

For "g" and "G", [the precision] specifies the
maximum number of digits to show,
including those prior to the decimal
point and those after it;

Note that leading zeros in the simple floating point representation are not counted as "digits".

There are some modules on CPAN that'll help you write a sprintf-like function. String::Sprintf is for adding a custom format or two to the regular sprintf formats. String::Formatter is for starting from scratch with a function that looks like sprintf but doesn't inherit any formats from it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文