Re: fractional cents

"A. Pagaltzis" <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Message-ID <20040419205228.GA6439@klangraum>
* Bernie Cosell <[email protected]> [2004-04-19 17:37]:
> So: what I want is something to format money correctly, whther
> it is fractional or not.  there's the fairly awful:
> 
>      sprintf ($amt =~ /\.\d\d\d/? "%7.3f": "%7.2f"), $amt

Right off the bat I thought of %g, but that doesn't really help:

    $ perl -e'printf "%7.4g\n", $_ for 1.2, 1.23, 1.234, 1.2345'
        1.2
       1.23
      1.234
      1.234

When testing $amt itself, I'd insist on using mathematical
functions only for the sake of cleanliness -- you never know when
stringification would surprise you. Unfortunately, getting the
fractional part of a number in Perl is verbose using mathematical
functions.

So instead I'd say to do string mangling on the end result, which
is only a string representation of $amt anyway:

    my $amt_str = sprintf "%7.3f", $amt;
    for($amt_str) { chop if /\.\d\d0\z/ } 

Test:

    perl -le'for (@ARGV) { $_ = sprintf "%7.3f", $_; \
    chop if /\.\d\d0\z/; print; }' 1.2, 1.23, 1.234, 1.2345
      1.20
      1.23
      1.234
      1.234
        
It's not shorter or more obvious I'm afraid, just a little more
correct.

-- 
Regards,
Aristotle
 
"If you can't laugh at yourself, you don't take life seriously enough."
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.