Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 373
Julio Diaz Avatar asked Feb 21 '11 23:02

Julio Diaz


People also ask

How do you remove decimal part?

Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point. (For example, if there are two numbers after the decimal point, then use 100, if there are three then use 1000, etc.) Step 3: Simplify (or reduce) the Rational number.

How do you shorten a decimal in Java?

format("%. 2f", height)); This will trim the double value to two decimal places.

How do you trim double value?

Shift the decimal of the given value to the given decimal point by multiplying 10^n. Take the floor of the number and divide the number by 10^n. The final value is the truncated value.


2 Answers

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   
like image 94
mikera Avatar answered Oct 26 '22 14:10

mikera


I think I got this one after further research

(format "%.2f"  4.21312312312312)

should return 4.21

like image 42
Julio Diaz Avatar answered Oct 26 '22 16:10

Julio Diaz