[plt-scheme] C-style Printf Format Convention?

From: Karl Pflästerer (sigurd at 12move.de)
Date: Wed May 12 12:31:50 EDT 2004

On 12 May 2004, ifconfig <- nslookupifconfig at hotmail.com wrote:

> If all you need is to choose the number of digits, why not write a function
> to do it? I don't think something exist in standard libraries.

No it doesn't exist (if you don't regard SLIB as kind of standard lib)
but printf from C can do much more than simply choosing the number of
digits. Furthermore the result gets rounded.

[...]
>> (limit-digits 12345.678901234567 20)
> "12345.678901234567"
>> (limit-digits 12345.678901234567 10)
> "12345.6789012345"
>> (limit-digits 12345.678901234567 5)
> "12345.67890"
>> (limit-digits 12345.678901234567 1)
> "12345.6"

I'll rewrite your examples in C.

#include <stdio.h>

int main (void)
{
  int prec[4] = {20, 10, 5, 1}; int i;
  for (i = 0; i < 4; i++)
    printf("%-10.*f\n", prec[i], 12345.678901234567);
  return (0);
}

The output is:
12345.67890123456709261518
12345.6789012346
12345.67890
12345.7   

You see the difference; (to see the exact meaning of the flags you
should perhaps read a man page or info page about printf).


   Karl
-- 
"Programs must be written for people to read, and only incidentally
for machines to execute."
                -- Abelson & Sussman, SICP (preface to the first edition)



Posted on the users mailing list.