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
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.
format("%. 2f", height)); This will trim the double value to two decimal places.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With