Search code examples
floating-pointformattinglispcommon-lisp

I wish to change the format of the numbers contained in a list Common Lisp Allegro


I have lists which contain numbers with too many decimals. I would like to recondition the list changing the format of the list elements. For instance I have '( 1.233453923729 3.44566546 9.1111111) and I would like to keep max two decimals.

I tried with a dolist to extract the list component to write them on a stream and to reread them after correcting the format. Actually I don't know how to write data on a string stream and then reading them again after format correction.


Solution

  • You can multiply your float by a power of 10, call FROUND and divide by the same factor:

    (defun round-float (float places)                      
      (check-type places (integer 1))
      (let ((factor (expt 10 places)))                     
        (/ (fround (* float factor)) factor)))
    

    Then you can apply the same function to all your floats using MAPCAR:

    (mapcar (lambda (f) (round-float f 2)) floats)