Search code examples
stringclojureoutputread-eval-print-loop

In Clojure, passing number with leading 0s to str causes strange behavior. What feature is this?


So, I accidentally figured this out while playing around with some strings.

(str 111) => "111"
(str 0111) => "73"

What is this?


Solution

  • Numbers prefixed with 0 are octal:

    0111
    => 73
    

    Numbers prefixed with 0x are hexadecimal:

    0x111
    => 273
    

    Numbers prefixed with Xr, where X is number from 2 to 36, have that radix:

    2r111
    => 7
    

    If you want to pad number with zeros, see format or cl-format:

    (format "%04d" 111)
    => "0111"
    
    (clojure.pprint/cl-format nil "~4,'0d" 111)
    => "0111"