home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / lang / lisp / mcl / 1234 < prev    next >
Encoding:
Text File  |  1992-08-14  |  2.1 KB  |  47 lines

  1. Path: sparky!uunet!olivea!apple!apple!cambridge.apple.com!wilcox@cmns.think.com
  2. From: wilcox@cmns.think.com
  3. Newsgroups: comp.lang.lisp.mcl
  4. Subject: _numtostring
  5. Message-ID: <9208142145.AA06224@cmns-sun.think.com>
  6. Date: 14 Aug 92 21:45:10 GMT
  7. References: Daniel Berger's message of Thu, 13 Aug 92 11:32:58 PDT <9208131832.AA01924@dewey>
  8. Sender: info-mcl-request@cambridge.apple.com
  9. Lines: 33
  10. Approved: comp.lang.lisp.mcl@Cambridge.Apple.C0M
  11. Original-To: berger@soe.berkeley.edu
  12. Original-Cc: info-mcl@cambridge.apple.com
  13.  
  14. I found a couple of bugs in the function float-to-string that I sent out
  15. earlier. Specifically, it did not work well for negative numbers or numbers
  16. which were slightly less than integers. Here's a revised version:
  17.  
  18. ;;; this function needs a better name
  19. (defun round-significand (number fractional-digits)
  20.   "Round the significand for display."
  21.   (if fractional-digits
  22.     (let ((divisor (expt 10 (- fractional-digits))))
  23.       (* (round number divisor) divisor))
  24.     (values number)
  25.     ))
  26.  
  27. ;;; this is a fast alternative to format for floating-point numbers
  28. ;;; with no exponent
  29. (defun float-to-string (number fractional-digits)
  30.   "Converts a floating-point number to a string, ~
  31.    with a given number of digits following the decimal point."
  32.   (multiple-value-bind (integral fractional)
  33.                        (truncate (round-significand number fractional-digits))
  34.     (let ((int-string (integer-to-string integral)))
  35.       ;; dont mess around with fractions if you dont have to
  36.       (if (zerop fractional-digits)
  37.         (concatenate 'string int-string ".")
  38.         (let* ((fract-int (* (expt 10 fractional-digits)
  39.                              ;; use abs because truncate signs the remainder
  40.                              (abs fractional)))
  41.                (fract-string (integer-to-string fract-int))
  42.                ;; pad fraction with enough zeros to separate it from decimal
  43.                (pad-string (make-string (- fractional-digits (length fract-string))
  44.                                         :initial-element #\0)))
  45.           (concatenate 'string int-string "." pad-string fract-string)
  46.           )))))
  47.