简体   繁体   English

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

[英]How to control floating-point formatting in Perl using 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?). 我通常使用%g ,但似乎指数位的数量是系统相关的 ,我不能像%.4g%.2g这样的变体工作(它们只产生相同的结果,不是吗?)。

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 (eg 10^5 > |x| > 10^-5), otherwise use scientific notation. 我真正想做的是如果数字(绝对值)在某个范围内(例如10 ^ 5> | x |> 10 ^ -5),则使用简单的浮点表示“如果可能”,否则使用科学计数法。 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...). 我也想限制显示的位数,比如5(所以我不会得到超大的浮点数,如0.12345678901234567890 ......)。

Some examples: 一些例子:

0.123456890 -> 0.12346 0.123456890 - > 0.12346

0.000000000123456 -> 1.23456e-10 0.000000000123456 - > 1.23456e-10

Can I do that directly in sprintf or do I have to write a special wrapper? 我可以直接在sprintf执行此操作,还是必须编写特殊的包装器?

No, you'd have to write a custom wrapper to get the behavior you describe: As perlfunc says: 不,你必须编写一个自定义包装器来获得你描述的行为:正如perlfunc所说:

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; 对于“g”和“G”,[精度]指定要显示的最大位数,包括小数点之前和之后的位数;

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. CPAN上有一些模块可以帮助你编写类似sprintf的函数。 String::Sprintf is for adding a custom format or two to the regular sprintf formats. String :: sprintf用于向常规sprintf格式添加一个或两个自定义格式。 String::Formatter is for starting from scratch with a function that looks like sprintf but doesn't inherit any formats from it. String :: Formatter用于从头开始,其函数看起来像sprintf但不从它继承任何格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM