Reputation: 29998
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?
Upvotes: 1
Views: 797
Reputation: 62109
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.
Upvotes: 4