Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string representation of float according to english locale with Clojure

Tags:

clojure

The locale on my machine is sv_SE.utf8, I want format to follow the conventions of en_GB.utf8 instead when formatting strings. Currently

(format "%f" 0.1) ; => 0,1

instead of

(format "%f" 0.1) ; => 0.1

It seems like I can't pass a locale to format. Is there any other way of working around this problem? I still want to keep using format due to its other capabilities.

like image 704
Rovanion Avatar asked May 31 '17 09:05

Rovanion


1 Answers

This works for me (my laptop default locale is set to fr-FR, France!):

(import java.util.Locale)
; => java.util.Locale

(defn my-format [fmt n & [locale]]
  (let [locale (if locale (Locale. locale)
                          (Locale/getDefault))]
    (String/format locale fmt (into-array Object [n]))))

; => #'dev/my-format

(my-format "%f" 0.1)
; => "0,100000"

(my-format "%f" 0.1 "en-GB")
; => "0.100000"

Any good?

like image 187
Scott Avatar answered Oct 01 '22 05:10

Scott