Search code examples
javaclojure

In Clojure or Java, how can I efficiently check whether a number is equivalent to an integer after rounding to two fractional digits?


I basically need a function in Clojure like rounds-to-int? which does the equivalent of this:

  • Take an arbitrary number (int, float or double)
  • Round it to at most two decimals (i.e. 1.000001234 => 1.00)
  • Determine whether the digits after the decimal point are both zero

e.g.

(rounds-to-int? 1) => true
(rounds-to-int? 1.234) => false
(rounds-to-int? 1.01) => false
(rounds-to-int? -1.01) => false
(rounds-to-int? 1.001) => true
(rounds-to-int? -1.001) => true
(rounds-to-int? 1.005) => false
(rounds-to-int? 1.004) => true

Any suggestions appreciated!


Solution

  • Here is the solution I came up with, and ended up using.

    (defn rounds-to-int?
      [value]
      (let [rounded (.setScale (bigdec value) 2 java.math.RoundingMode/HALF_UP)]
        (== (int rounded) rounded)))