以下是我的数字舍入函数。。。前2组合用于将以0或5(0,5,10,15,20,…)结尾的第一个最近数上的任何数字四舍五入
我的最后一个函数(d轮)是您实际需要的函数。。。只需提供您想要舍入的数字,对于舍入格式的小数,您提供0.5。。。
- (defun fixx ( n / remi r )
- (setq remi (- n (fix n)))
- (if (< remi 0.5) (setq r (fix n)))
- (if (>= remi 0.5) (setq r (+ (fix n) 1)))
- r
- )
- (defun round ( n / ldig r )
- (setq ldig (- n (* (fix (/ n 10.0)) 10)))
- (if (< -0.5 ldig 3) (setq r (* (fix (/ n 10.0)) 10)))
- (if (< 2 ldig (setq r (+ (* (fix (/ n 10.0)) 10) 5)))
- (if (< 7 ldig 9.5) (setq r (+ (* (fix (/ n 10.0)) 10) 10)))
- r
- )
- (round 7.2) => 10
- (round 7.3) => 10
- (round 7.5) => 10
- (round 7.7) => 10
- (round 7. => 10
- (fixx 7.2) => 7
- (fixx 7.3) => 7
- (fixx 7.5) => 8
- (fixx 7.7) => 8
- (fixx 7. => 8
- (round (fixx 7.2)) => 5
- (round (fixx 7.3)) => 5
- (round (fixx 7.5)) => 10
- (round (fixx 7.7)) => 10
- (round (fixx 7.) => 10
- (defun _round ( n d )
- (if (< (- n (* (fix (/ n d)) d)) (/ d 2.0))
- (* (fix (/ n d)) d)
- (* (+ 1.0 (fix (/ n d))) d)
- )
- )
- (_round 7.2 0.5) => 7.0
- (_round 7.3 0.5) => 7.5
- (_round 7.5 0.5) => 7.5
- (_round 7.7 0.5) => 7.5
- (_round 7.8 0.5) => 8.0
虽然你已经有了一个案例(代码)的答案,也许你会发现这些也很有用。。。
M、 R。 |