rounding off a value

caderudite

Usenet Archive
Joined
Jul 28, 2003
Messages
17
Reaction score
0
hello people, want to round off a value to it's nearest integer. like i want 5.85 to become 6 and 5.25 become 5. Fix is converting to 5 whether it's 5.25 or 5.95. thanks
 
(setq x 4.4)

(fix(+ 0.5 x))

:-)

like RK said, check the previous knowlege base on this - it's out there

"caderudite" <> wrote:

adding 0.5 seems very easy
ex: (Setq x 4.5)
(fix (+ 0.5 x))
 
;;by Doug Broad
(defun round (value to)
(setq to (abs to))
(* to (fix (/ ((if (minusp value) - +) value (* to 0.5)) to)))
)

Examples:
Command: (round 5.25 1)
5
Command: (round 5.85 1)
6
Command: (round 5.85 1.0)
6.0

Note: if the value suppied to the "to" argument is a real, a real is returned.

Joe Burke
 
An Improved version to (FIX)

rounds numbers to either upper or lower value.

(AutoLISP native function FIX always rounds

numbers to the nearest lower integer).

;CODING BEGINS HERE

(defun fixx (realnum)

(if (> realnum (+ (fix realnum) 0.5))

(setq realnum (1+ (fix realnum)))

(setq realnum (fix realnum))

)

realnum

)

;CODING ENDS HERE

Examples :

(fixx 1.3) returns 1

(fixx 1.6) returns 2 (AutoLISP's FIX would have returned 1)

(fixx 1.50000001) returns 2

(fixx 1.49999999) returns 1

(fixx 1.49999999999) returns 1

(fixx 1.50000000001) returns 2

(fixx 0.0001) returns 0

(fixx 0.9999999) returns 1

"caderudite" <> wrote:

hello people, want to round off a value to it's nearest integer. like i want 5.85 to become 6 and 5.25 become 5. Fix is converting to 5 whether it's 5.25 or 5.95. thanks
 
Kenny,

Command: (fixx 1.2)
1
Command: (fixx 1.7)
2
Command: (fixx -1.2)
-1
Command: (fixx -1.7)
-1 < oops

Command: (round -1.7 1)
-2

Joe Burke
 
allows rounding to specified place.

(defun rnd (num place)
(if (numberp num)
(if (zerop place)
(fix (distof (rtos num 2 0)))
(distof (rtos num 2 place))
))
)

caderudite said:
hello people, want to round off a value to it's nearest integer.
like i want 5.85 to become 6 and 5.25 become 5. Fix is converting to 5 whether it's 5.25 or 5.95. thanks
 
Kenny,

If you are still checking this thread, and you are interested in a fix for fixx dealing with negative numbers. Take a look at the function Ken posted. The rounding function is rtos. The string is converted back to a number using distof. That could also be done with atoi or atof depending on what you want the function to return. Notice there's no math involved. Which avoids a bunch of complexity given what fixx is trying to do.

;; your function
(defun fixx (realnum)
(if (> realnum (+ (fix realnum) 0.5))
(setq realnum (1+ (fix realnum)))
(setq realnum (fix realnum))
)
realnum
)

;; alternative
(defun fixx (realnum)
(atof (rtos realnum 2 0))
)

Offered with the thought it isn't fair to criticize, without providing a solution.

Regards
Joe Burke
 

Latest threads

Back
Top