[plt-scheme] C-style Printf Format Convention?
On May 12, 2004, at 5:07 AM, ifconfig wrote:
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
> 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.
>
> (define (limit-digits x num)
> ; x - number, num - number of digits after the decimal point
> (define (iter l n t)
> ; l - the number-string, as a list
> ; n - number of digits left
> ; t - has decimal point been encountered yet?
> (if t
> (if (> n 0)
> (cons (car l) (iter (cdr l) (- n 1) #t))
> empty)
> (cons (car l) (iter (cdr l) n (equal? (car l) #\.)))))
> (list->string (iter (string->list (number->string x)) n #f)))
>
>
>> (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"
Gluurg. How about something simple and numeric:
;; warning! untested code alert!
(define (limit-digits x num)
(let ([y (expt 10 x)])
(number->string (/ (exact->inexact (round (* num y))) y))))
... or something like that. Plus, this code rounds rather than
truncating.
john
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2169 bytes
Desc: not available
URL: <http://lists.racket-lang.org/users/archive/attachments/20040512/0e48b18c/attachment.p7s>