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

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

am 31.03.2008 22:10:46 von xhoster

jidanni@jidanni.org 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?

Xho

--
-------------------- http://NewsReader.Com/ --------------------
The costs of publication of this article were defrayed in part by the
payment of page charges. This article must therefore be hereby marked
advertisement in accordance with 18 U.S.C. Section 1734 solely to indicate
this fact.

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

am 31.03.2008 22:55:16 von Ben Morrow

Quoth xhoster@gmail.com:
> jidanni@jidanni.org 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