11

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...

viebel
  • 19,372
  • 10
  • 49
  • 83
  • there is no with-precision in cljs – edbond Feb 04 '14 at 14:46
  • @edbond, how do I know what parts of `clojure` are available in `cljs`? – viebel Feb 04 '14 at 17:18
  • some info here - https://github.com/clojure/clojurescript/wiki/Differences-from-Clojure Also pay attention to warnings: `WARNING: Use of undeclared Var some-namespace/with-precision at line 430` – edbond Feb 04 '14 at 17:34

3 Answers3

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

(.log js/console (gstring/format "%.2f" 1.2345))
Timothy Pratley
  • 10,586
  • 3
  • 34
  • 63
  • Interestingly Google Closure [specifically says](https://google.github.io/closure-library/api/goog.string.format.html) to use `.toFixed` in simple cases! – Jeremy Field Nov 04 '20 at 10:10
  • Yes, I think `.toFixed` is better for this example. The correct answer seems to be "you are doing it right" :) – Timothy Pratley Nov 04 '20 at 20:30
11
(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.

Alesya Huzik
  • 1,520
  • 14
  • 17
2
(defn round-number 
   [f]
   (/ (.round js/Math (* 100 f)) 100))

If you want to keep it as number type (inspired by javascript reply)

Michel A.
  • 201
  • 2
  • 8