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

3

12

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

Eldoneldora answered 4/2, 2014 at 13:42 Comment(3)
there is no with-precision in cljsPersonage
@edbond, how do I know what parts of clojure are available in cljs?Eldoneldora
some info here - github.com/clojure/clojurescript/wiki/Differences-from-Clojure Also pay attention to warnings: WARNING: Use of undeclared Var some-namespace/with-precision at line 430Personage
C
17
(ns foo.bar
  (:require
    [goog.string :as gstring]
    [goog.string.format]))

(.log js/console (gstring/format "%.2f" 1.2345))
Cog answered 7/10, 2014 at 23:3 Comment(2)
Interestingly Google Closure specifically says to use .toFixed in simple cases!Quietly
Yes, I think .toFixed is better for this example. The correct answer seems to be "you are doing it right" :)Cog
D
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.

Disembark answered 13/12, 2015 at 21:45 Comment(0)
E
3
(defn round-number 
   [f]
   (/ (.round js/Math (* 100 f)) 100))

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

Ellon answered 28/2, 2019 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.