Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding numbers to n decimals in clojure

Tags:

clojure

When I do, for example, (/ 1.0 7.0), I only get 17 digits: 0.14285714285714285. How can I get more then that?

like image 342
panther tamer Avatar asked Aug 18 '11 15:08

panther tamer


People also ask

How to round decimals to a number of decimal places in Clojure?

To round bigdec s to a number of decimal places in Clojure the only solution I have found is to use Java interop: Show activity on this post. Using the function Double/ParseDouble after using format on the decimal number will return a decimal rounded to the desired number of decimals described by using format. Like so:

How do you round decimal values?

Use the following steps as a guide to round decimal values quickly and easily: 1. Determine the place value of the last digit in the number To round a decimal value, look at the last place value of the number with which you're working. For instance, in the number 76.287, the last place value after the decimal point is the thousandth place.

How can I format every number in a sequence in Clojure?

Then you can simply map round2 over the sequence to format every number at once: This is more useful for a longer sequence, of course. Another option is to use cl-format, which is a Clojure implementation of Common Lisp's format.

Why do we round decimals to the nearest hundredth place?

Depending on the purpose of your computation (like adding up price values), it's common to round decimals to the nearest hundredth place. This means you estimate what the value would be if you were to approximate the number using the thousandth place as an indicator.


2 Answers

Use BigDecimal numbers and with-precision:

(with-precision 50 (/ 1M 7))
=> 0.14285714285714285714285714285714285714285714285714M
like image 142
Justin Kramer Avatar answered Oct 02 '22 07:10

Justin Kramer


Clojure (and pretty much all lisps) has ratio type that way you do not lose precision. do all your calculations with ratio and convert to double/float at the last minute to avoid precision problems.

like image 25
Hamza Yerlikaya Avatar answered Oct 02 '22 09:10

Hamza Yerlikaya