zero-padding and truncating with string formats in Clojurescript

Table of Contents

One of the discrepancies between Clojure and Clojurescript is that the javascript version doesn’t have anything like the classic Unix/C-style string format functions. Some functionality is not simply reproducible with clever uses of str, but fortunately Google Closure is here to save the day. Because Closure is part of Clojurescript, there are no added project dependencies to make this work.

(ns myapp.services
  (:require 
    [goog.string :as gstring]
    [goog.string.format]))

(str "$" (gstring/format "%.2f" 2.5)) ; truncated to two decimal places (not the same as rounding, 
                                        ; which may change digits

(str "$" (gstring/format "%02d" 2)) ; 02 : padded with zeroes so it always has at least two digits

Resources

Tory Anderson avatar
Tory Anderson
Full-time Web App Engineer, Digital Humanist, Researcher, Computer Psychologist