Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ClojureScript, how to display a float with 2 decimals?

I have tried to use with-precision but it didn't work:

(.log js/console (with-precision 2 1.2345)) 

So I have used toFixed:

(.log js/console (.toFixed 1.2345 2)) 

But I feel it's not the idiomatic way of doing that.

In addition, I don't understand why with-precision doesn't work.

Please inspire me...

like image 994
viebel Avatar asked Feb 04 '14 13:02

viebel


2 Answers

(ns foo.bar
  (:require
    [goog.string :as gstring]
    [goog.string.format]))

(.log js/console (gstring/format "%.2f" 1.2345))
like image 121
Timothy Pratley Avatar answered Oct 19 '22 03:10

Timothy Pratley


(ns foo.bar
  (:require [cljs.pprint :as pprint]))

(pprint/cl-format nil  "~,2f" 1.2345) ; => returns "1.23"
(pprint/cl-format true "~,2f" 1.2345) ; => prints "1.23", returns nil

Same code could be used in Clojure if you swap cljs.pprint with clojure.pprint.

like image 20
Alesya Huzik Avatar answered Oct 19 '22 02:10

Alesya Huzik