Search code examples
clojureclojure-java-interop

How does Clojure on the JVM convert from a float to a double with trailing garbage digits?


I run:

(double (float 3.14159))

and I get:

3.141590118408203

If I run it down to:

(double (float 3.141))

I get: 3.1410000324249268

By what method is this conversion happening?


Solution

  • This is related to general precision problem with floating point operations; floating points on computers do not map directly to decimal numbers, so standard decimal display of floats and doubles is rounded. In other words; the float and double here have exactly the same value, but when displayed they are rounded differently.

    => (= (double (float 3.14159)) (float 3.14159))
    true
    

    On the JVM, Why converting from float to double changes the value? and Convert float to double without losing precision may help.