开发者

How do I trim the decimal of a number using clojure or jython?

开发者 https://www.devze.com 2023-02-12 05:34 出处:网络
In clojure or jython: say I have a number 4.21312312312312 how can i get a number with just the first 2 decimals. It开发者_运维百科 would return 4.21 for the example above.

In clojure or jython: say I have a number 4.21312312312312 how can i get a number with just the first 2 decimals. It开发者_运维百科 would return 4.21 for the example above. Thanks


Clojure has a round function in clojure.contrib.math - it's probably best to use this one assuming you want correct behaviour with all the different possible numerical types that Clojure can handle.

In which case, and assuming you want the result as an arbitrary-precision BigDecimal, an easy approach is to build a little helper function as follows:

(use 'clojure.contrib.math)

(defn round-places [number decimals]
  (let [factor (expt 10 decimals)]
    (bigdec (/ (round (* factor number)) factor))))

(round-places 4.21312312312312 2)
=> 4.21M   


I think I got this one after further research

(format "%.2f"  4.21312312312312)

should return 4.21


Multiply by 10^numberofdecimals you want, round, and then divide. This doesn't guarantee the string representation will be rounded correctly, but should work most of the time. For example:

(* 0.01 (Math/round (* 100 (float (/ 7 8)))))

Yielding 0.88


Taking it one step further, you could parametize the number of decimal places:

(defn- factor [no-of-decimal-places]
    (.pow (BigInteger. "10") no-of-decimal-places))

(defn truncate [value decimal-places]
  (let [divide-and-multiply-by (factor decimal-places)]
    (float (/ (int (* divide-and-multiply-by value)) divide-and-multiply-by))))

(truncate 2.23999999 2)
=> 2.23

(truncate 2.23999999 3)
=> 2.239

(truncate 2.23999999 4)
=> 2.2399


Found this thread looking for a similar truncation answer.

Not sure if there is a better solution, but came up with the following.

For non-rounding, you can multiple by 100 (for 2 decimal places, 1000 for 3 etc), turn into an integer and then divide by the original factor, before converting to a float for numeric output. For example:

(float (/ (int (* 100 123.1299)) 100))
=> 123.12

(float (/ (int (* 100 123.1209)) 100))
=> 123.12
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号