Re: printf: zero pad after the decimal a given amount




Quoth xhoster@xxxxxxxxx:
jidanni@xxxxxxxxxxx wrote:
Why is there no way to tell printf to zero pad like the right column:

One reason is that what you want is ill-defined. If we are going to tweak
sprintf to make it suit our personal preferences, I'd rather see a
conversion character that behaved just like %f if given a good number, but
returned the empty string if given either an empty string or undef (rather
than converting it to zero and then applying %f to the zero.)

0.1 :0.100
0.05 :0.050
0.03 :0.030
0.025 :0.025
0.02 :0.020
0.015 :0.015

Apparently you want to preserve non-zero digits even if that means going
beyond 3 digits right of the decimal. But why did you stop at 4?

0.014999999999999999444888

0.0125 :0.0125


0.0125000000000000006938893

How many consecutive zeros or nines are needed before you decide there are
enough to ignore what is the right of them?

It appears to me the OP wants either 3 s.f. after the point or 3 places,
whichever comes out shorter. Something like

sub fmt {
return
map /(\d*\.\d{3}\d*?)0*$/,
map /(\d*\.0*[1-9]\d\d)/,
map { sprintf "%.308f", $_ }
@_;
}

appears to work, but it's hardly pretty :(. The 308 is the number of
places required to represent DBL_MIN with 53-bit doubles; if your perl
is using 64-bit long doubles you will need 4932 instead.

Ben

.



Relevant Pages

  • Re: printf: zero pad after the decimal a given amount
    ... returned the empty string if given either an empty string or undef (rather ... than converting it to zero and then applying %f to the zero.) ... Apparently you want to preserve non-zero digits even if that means going ...
    (comp.lang.perl.misc)
  • Re: Coerce Null to Zero?
    ... Is there a similar technique for coercing it to Zero with numeric fields? ... lRes = Val) ... I prefer an empty string to zero as a default value, ...
    (microsoft.public.vb.syntax)
  • Re: C ++ help!
    ... doubles and I am using a loop to calculate doubles up to an ... at the beginning i get normal approximations and then ... So next line you divide by zero so y is undefined ... Registered Linux User #300464 Machine Id #188886 ...
    (comp.programming)
  • Re: Coerce Null to Zero?
    ... IOW, just consider the field at its ... lRes = Val) ... I prefer an empty string to zero as a default value, ...
    (microsoft.public.vb.syntax)
  • RE: How does defined work?
    ... Both Zero "0" and empty string " " are defined values in Perl, ... ||I am posting this query in beginners instead of beginners-cgi because I ... ||How can I make this execute the die statement when userId is missing from ...
    (perl.beginners)