Arc Forumnew | comments | leaders | submitlogin
2 points by eds 5936 days ago | link | parent

Another thing (which I feel I really ought to already know the answer for...), how do you format floating point numbers (say, to three decimal places)? I could do this trivially with #'format in CL, but I don't see anything in the Arc docs to help me, and I don't know enough about Scheme to hack around it with ($ ...).


2 points by almkglor 5936 days ago | link

Arc doesn't have any.

If it's always N decimal places of a reasonable number, you can do magic stuff like:

  (def to-N-places (f (o N 3))
    (with (fact (let rv 1
                  (repeat N (zap * rv 10))
                  rv)
           float [+ _ 0.0])
      (pr:/ (float:floor:* f fact) (float fact))))
It won't pad though.

-----

3 points by eds 5935 days ago | link

Your version doesn't round.

  arc> (do (to-N-places 5.123456789 5) (prn))
  5.12345
  nil
But the following function will.

  (def to-N-places (f (o N 3))
    (let s (string (to-nearest f (expt 10.0 (- N))))
      (cut s 0 (min (+ N 1 (pos #\. s)) (len s)))))

  arc> (to-N-places 5.123456789 5)
  "5.12346"
(That said, there may be other problems with it.)

Personally, I think we really need CL-style format.

-----

1 point by eds 5932 days ago | link

After a bit more searching, I finally found a page on printing numbers in the scheme cookbook (http://schemecookbook.org/Cookbook/NumberPrinting), specifically the first example which uses SRFI 48 for some basic formatting support (http://srfi.schemers.org/srfi-48/srfi-48.html). The following to works in Anarki/MzScheme 352.

  arc> ($ (require (lib "48.ss" "srfi")))
  #<void>
  arc> (def format args ($ (format ,@args)))
  #<procedure: format>
  arc> (format "~4,4F" (sqrt 2))
  "1.4142"
Enjoy ;-)

-----

2 points by tokipin 5935 days ago | link

'to-nearest might help:

http://arcfn.com/doc/math.html#to-nearest

-----

1 point by eds 5935 days ago | link

  arc> (to-nearest 5.123 .1)
  5.1000000000000005
Um...

-----