Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my string formatting failing in Clojure?

In Java, I can do the following to format a floating point number for display:

String output = String.format("%2f" 5.0);
System.out.println(output);

In theory, I should be able to do the same thing with this Clojure:

(let [output (String/format "%2f" 5.0)]
    (println output))

However, when I run the above Clojure snippet in the REPL, I get the following exception:

java.lang.Double cannot be cast to [Ljava.lang.Object;
[Thrown class java.lang.ClassCastException

What am I doing wrong?

like image 287
quanticle Avatar asked Feb 18 '12 18:02

quanticle


1 Answers

Java's String.format takes an Object[] (or Object...), to use String.format in Clojure you need to wrap your arguments in an array:

(String/format "%2f" (into-array [5.0]))

Clojure provides a wrapper for format that's easier to use:

(format "%2f" 5.0)

Kyle

like image 86
Kyle Burton Avatar answered Nov 05 '22 23:11

Kyle Burton