1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

任意の単位での切り捨て、切り上げ、四捨五入

Posted at

めもめも

round.clj
(defn half [x] (/ x 2))
(defn floor [value unit]
  {:pre [(pos? unit)]}
  (cond
   (Double/isNaN value) value
   (Double/isInfinite value) value
   :else  (let [q (quot value unit)]
            (* unit (if (neg? (rem value unit))
                      (dec q) q)))))

(defn ceil [value unit]
  (- (floor (- value) unit)))

(defn round [value unit]
  (floor (+ value (half unit)) unit))
結果
(floor 3.7 2.5)  ;2.5
(ceil 3.7 2.5)   ;5.0
(round 3.7 2.5)  ;2.5
(round 3.8 2.5)  ;5.0
(floor 12.34 0.1);12.3
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?