Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a ratio as a percentage in Clojure

This seems like it should be obvious, but how do you convert Clojure's ratio type to a percentage?

(format "%3s" (/ 1 2))
;; "1/2"

(format "%3f" (/ 1 2))
;; Throws an error
like image 707
wegry Avatar asked Dec 04 '22 02:12

wegry


2 Answers

You can always convert to Float:

(format "%3f" (float (/ 1 2)))
like image 187
zero323 Avatar answered Jan 11 '23 16:01

zero323


cl-format, which is derived from Common Lisp's format, is more flexible than Clojure's Java-based format in some situations:

(require 'clojure.pprint)
(clojure.pprint/cl-format nil "~f" (/ 1 2)) ;=> "0.5"
like image 38
Mars Avatar answered Jan 11 '23 16:01

Mars