Search code examples
javascriptlocalizationclojurescript

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.


Solution

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