wegry
wegry

Reputation: 8147

Currency formatting in Clojurescript

In Javascript to do locale based formatting of a currency, you do

(550.753).toLocaleString(undefined, {style: 'currency', currency: 'USD'})
// # $550.75 in en-US

How do you do the same in Clojurescript?

I've tried

(.toLocaleString 550.753 nil {:style "currency" :currency "USD"}) 

to no avail.

Upvotes: 4

Views: 1071

Answers (2)

Max Prokopov
Max Prokopov

Reputation: 1336

Since Clojurescript is using Google Closure library extensively, you can leverage it's i18n currency formatting functions

(import '[goog.i18n NumberFormat]
        '[goog.i18n currency])

(let [fmt (NumberFormat. (.getLocalCurrencyPattern currency "USD"))]
  (.format fmt 123.456)) ;; => "$123,46"

Upvotes: 2

Daniel Compton
Daniel Compton

Reputation: 14569

Running your JS sample, I get Uncaught TypeError: Cannot convert undefined or null to object(…) because you're passing null as a locale. The same error happens in ClojureScript too. toLocaleString requires you pass it a locale.

Fixing this to provide the de-DE locale:

JavaScript:

(550.753).toLocaleString('de-DE', {style: 'currency', currency: 'EUR'})
// "550,75 €"

ClojureScript:

(.toLocaleString 550.753 "de-DE" #js {:style "currency" :currency "USD"})
;; "550,75 $"

#js is used to convert a ClojureScript map into a JavaScript Object.

If you want to use the default locale instead, pass either #js [], or js/undefined.

Upvotes: 4

Related Questions