Bill Tillman Posted May 28, 2014 Posted May 28, 2014 I've been toying around with a few things today but can't seem to hit on the right code which will take a number and round it up to the nearest 1/2". That's only if it's not a whole integer in the first place. 3" = 3" 3.25" = 3.5" 4" = 4" 4.625" = 5" etc .... Quote
MSasu Posted May 28, 2014 Posted May 28, 2014 Rough approach: (defun Round05( theNumber / theRem ) (setq theRem (rem theNumber 1)) (cond ((= theRem 0.0) theNumber) ((and (> theRem 0.0) (< theRem 0.25)) (* (fix theNumber) 1.0)) ((and (>= theRem 0.25) (< theRem 0.75)) (+ (fix theNumber) 0.5)) ((>= theRem 0.75) (+ (fix theNumber) 1.0)) ) ) May be further refined to work for negative values, too. Quote
Bill Tillman Posted May 28, 2014 Author Posted May 28, 2014 MSasu, Thank you. I created a nice function in VB.NET a few weeks ago to do this but was having some trouble adopting it to LISP. This works perfectly. Quote
MSasu Posted May 28, 2014 Posted May 28, 2014 Glad to hear that worked for you; you're welcome! Out of curiosity, what weren't posible to be translated from your VB code? Quote
Lee Mac Posted May 28, 2014 Posted May 28, 2014 Another version, also accepts negatives: ;; Round Up - Lee Mac ;; Rounds 'n' up to the nearest 'm' (defun LM:roundup ( n m ) (cond ((equal 0.0 (rem n m) 1e- n) ((< n 0) (- n (rem n m))) ((+ n (- m (rem n m)))) ) ) _$ (LM:roundup 3 0.5) 3 _$ (LM:roundup 3.25 0.5) 3.5 _$ (LM:roundup 4 0.5) 4 _$ (LM:roundup 4.625 0.5) 5.0 Quote
VVA Posted May 29, 2014 Posted May 29, 2014 Another version (defun round (num prec) (* prec (if (minusp num) (fix (- (/ num prec) 0.5)) (fix (+ (/ num prec) 0.5)) ) ) ) $ (round 3.25 0.5) 3.5 _$ (round -3.25 0.5) -3.5 _$ (round -3.75 0.5) -4.0 Quote
Bill Tillman Posted May 29, 2014 Author Posted May 29, 2014 Thanks everyone. I now have a plethora of functions for this. I'm going to tinker with converting my VB.NET code over the weekend. I'll post how that came out later. VB.NET Code ' This handles any non-integer input and rounds the user's input up to the nearest vDenominator ' In this case we use 1/16" and it remember it rounds up, not down. Public Function RoundFraction(ByVal x As Double, ByVal vDenominator As Integer) As Double If (x - Int(x)) * vDenominator <> Int((x - Int(x)) * vDenominator) Then x = (Int((x - Int(x)) * vDenominator) + 1) / vDenominator + Int(x) End If Return x End Function I call this like so: RoundFraction(4.4231, 16) And it comes back with 4.4375. This corrects for when the user puts in a strange dimension that's at least close enough to what they want. Quote
Recommended Posts
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.