Rounding Functions
Introduction
Here are various functions which may be used to round real valued arguments (doubles) to various multiple or decimal places.
Contents
Round to the Nearest Integer
Select all
;; Round - Lee Mac ;; Rounds 'n' to the nearest integer (defun LM:round ( n ) (fix (+ n (if (minusp n) -0.5 0.5))) )
Examples
_$ (LM:round 1.23) 1 _$ (LM:round 4.56) 5 _$ (LM:round -1.23) -1 _$ (LM:round -4.56) -5
Round to the Nearest Multiple
Select all
;; Round Multiple - Lee Mac ;; Rounds 'n' to the nearest multiple of 'm' (defun LM:roundm ( n m ) (* m (fix ((if (minusp n) - +) (/ n (float m)) 0.5))) )
Alternative Version
Select all
;; Round Multiple - Lee Mac ;; Rounds 'n' to the nearest multiple of 'm' (defun LM:roundm ( n m ) (* m (atoi (rtos (/ n (float m)) 2 0))) )
Examples
_$ (LM:roundm 1.23 0.2) 1.2 _$ (LM:roundm 4.56 0.2) 4.6 _$ (LM:roundm -3.21 2) -4 _$ (LM:roundm -4.56 2) -4
Round to Decimal Places
Select all
;; Round To - Lee Mac ;; Rounds 'n' to 'p' decimal places (defun LM:roundto ( n p ) (LM:roundm n (expt 10.0 (- p))) )
Examples
_$ (LM:roundto 1.5252 0) 2.0 _$ (LM:roundto 1.5252 1) 1.5 _$ (LM:roundto 1.5252 2) 1.53 _$ (LM:roundto 1.5252 3) 1.525
Round Up to the Next Multiple
Select all
;; Round Up - Lee Mac ;; Rounds 'n' up to the nearest 'm' (defun LM:roundup ( n m ) ((lambda ( r ) (cond ((equal 0.0 r 1e-8) n) ((< n 0) (- n r)) ((+ n (- m r))))) (rem n m)) )
Examples
_$ (LM:roundup 2.01 2) 4.0 _$ (LM:roundup -1.99 2) 0.0
Round Down to the Next Multiple
Select all
;; Round Down - Lee Mac ;; Rounds 'n' down to the nearest 'm' (defun LM:rounddown ( n m ) ((lambda ( r ) (cond ((equal 0.0 r 1e-8) n) ((< n 0) (- n r m)) ((- n r)))) (rem n m)) )
Examples
_$ (LM:rounddown 2.01 2) 2.0 _$ (LM:rounddown -1.99 2) -2.0