Nick
Nick

Reputation: 9061

How to format numbers using space as separater in Clojure?

For example, I can format using comma as separater:

(format "%,d"(BigInteger. "fffff" 16))
;=> 1,048,575

Is it possible to use space instead:

1 048 575 ?

Upvotes: 2

Views: 2099

Answers (3)

Symfrog
Symfrog

Reputation: 3418

I do not think this is possible using java.util.Formatter (which is what clojure.core/format ultimately uses). The code below, however, will produce the desired outcome:

(import 'java.text.DecimalFormatSymbols
        'java.text.DecimalFormat
        'java.text.FieldPosition)

(defn format-bigint [i]
  (let [format (DecimalFormatSymbols.)
        out (StringBuffer.)]
    (.setGroupingSeparator format \space)
    (.format (DecimalFormat. ",###" format) i out (FieldPosition. java.text.NumberFormat/INTEGER_FIELD))
    (.toString out)))

Upvotes: 1

schaueho
schaueho

Reputation: 3504

You could use cl-format from clojure.pprint, which is an implementation of Common Lisp's rather extensive and very powerful format

 user=> (cl-format nil "The answer is ~,,' :D" 123456789)
 "The answer is 123 456 789"

CL's cl-format has, like Clojure's regular format, several directives, here D for digits. The : modifier tells it to print commas between groups of digits, however, the ' behind the second comma specifies to use a space as the comma-character to use.

Upvotes: 7

ntalbs
ntalbs

Reputation: 29458

I'm not sure this is the best way, however, you can safely replace , with space. Anyway, after the number is formatted, it's just a string.

(clojure.string/replace (format "%,d" (BigInteger. "fffff" 16)) "," " ")

I tried to use java.text.DecimalFormat, and set the grouping separator by setGroupingSeparator method of java.text.DecimalFormatSymbols, but failed.

Upvotes: 3

Related Questions