Jump to content

Cut to n decimal places


Isaac26a

Recommended Posts

Well I was asking myself how to cut a number lets say 456.56798 to 3 decimal places, I have tried with (rtos 456.56798 2 3) but then I noticed that it always round up to 456.568, so I did the following

(vl-load-com)
(defun c:IA:cut (/ a b c decimalplaces number)
   (setvar "cmdecho" 0)
   (vl-cmdf "_.undo" "_begin")
   (setq number (getreal "\nType the number to cut: ")
         decimalplaces (getint "\nType the decimal places: ")
         a (atof (rtos number 2 decimalplaces))
         b (- number a)
   )
   (if (or (> b 0) (zerop b))
      (princ (strcat "\nYour new number is: " (rtos a 2 decimalplaces)))
      (progn
         (setq c (+ (/ 1.0 (expt 10 decimalplaces)) b)
               a (- number c)
         )
         (princ (strcat "\nYour new number is: " (rtos a 2 decimalplaces)))
      )
   )

   (vl-cmdf "_.undo" "_end")
   (princ)
)

Just hope it helps you with your programs.

Link to comment
Share on other sites

Here are two other possible methods:

(defun f1 ( n p )
    (/ (fix (* n (expt 10 p))) (expt 10.0 p))
)
_$ (f1 456.56798 3)
456.567
(defun f2 ( n p / d s )
    (setq d (getvar 'dimzin))
    (setvar 'dimzin 0)
    (setq s (rtos n 2 16)
          s (substr s 1 (+ 1 p (cond ((vl-string-position 46 s)) ((strlen s)))))
    )
    (setvar 'dimzin d)
    (atof s)
)
_$ (f2 456.56798 3)
456.567

 

Edited by Lee Mac
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...