Re: [SLUG] truncation in dc

From: Paul M Foster (paulf@quillandmouse.com)
Date: Sun Jul 08 2007 - 20:33:37 EDT


Folks:

Here's a reply from Wayne Pollock, the fellow who sponsors our Tampa
meetings.

Paul:

Please post the following for me on the SLUG list. As
you know, a digest subscriber such as myself is not
allowed to post directly. Thanks!

-Wayne

----------------------------------------------------------------

Eben King wrote:
> > Anyone know how to truncate values in dc(1)? I RTFMed but couldn't
> > find it. For example:
> >
> > If I set the precision to three places:
> >
> > 3k
> >
> > and then calculate 1/3:
> >
> > 1 3/p
> > .333
> >
> > It's correct. Supposing I only want one place to the right of the
> > decimal point:
> >
> > 1k
> >
> > Adding 0 or 0.0, or multiplying by 1 or 1.0 won't work:
> >
> > 0+p
> > .333
> > 0.0+p
> > .333
> >
> > 1*p
> > .333
> > 1.0*p
> > .333
> >
> > So how do I do it?

Output formatting is very absent from dc and bc.
You should either do your math in awk (which is
a standard POSIX utility that supports printf),
use a Perl one liner, or even the shell's printf
command to post-process the numbers produced
by bc and dc.

In dc you have to do rounding the old-fashioned way:
dc -e '3k 1 3 / 10 * .5 + 1k 10 / p'
.3

In awk:
$ awk 'BEGIN {printf "%.1f\n", 1 / 3}'
0.3

In Perl:
$ perl -e 'printf( "%.1f\n", 1 / 3);'
0.3

In dc with (a POSIX) shell for formatting:
$ printf '%.1f\n' $(dc -e '3k 1 3 / p')
0.3

Hope this helps!

-Wayne Pollock

-- 
Paul M. Foster --
Paul M. Foster
-----------------------------------------------------------------------
This list is provided as an unmoderated internet service by Networked
Knowledge Systems (NKS).  Views and opinions expressed in messages
posted are those of the author and do not necessarily reflect the
official policy or position of NKS or any of its employees.



This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 17:51:24 EDT