Number Parsing in Clojure

Our first program will demonstrate number parsing in Clojure. Here’s the full source code with explanations:

(ns number-parsing
  (:require [clojure.edn :as edn]))

;; Parse a floating-point number
(def f (edn/read-string "1.234"))
(println f)

;; Parse an integer
(def i (edn/read-string "123"))
(println i)

;; Parse a hexadecimal number
(def d (edn/read-string "0x1c8"))
(println d)

;; Parse an unsigned integer (in Clojure, all integers are signed)
(def u (edn/read-string "789"))
(println u)

;; Parse a string to integer (similar to Atoi)
(def k (Integer/parseInt "135"))
(println k)

;; Handling parsing errors
(try
  (Integer/parseInt "wat")
  (catch NumberFormatException e
    (println (.getMessage e))))

In Clojure, we use the clojure.edn/read-string function to parse numbers from strings. This function can handle various number formats, including floating-point numbers, integers, and hexadecimal numbers.

For read-string, there’s no need to specify precision bits as Clojure uses arbitrary-precision arithmetic by default.

To parse a string specifically as an integer, we can use the Integer/parseInt function, which is similar to the Atoi function in other languages.

When parsing fails, Clojure will throw exceptions. We can catch these exceptions to handle parsing errors gracefully.

To run the program, save it as number_parsing.clj and use the clj command:

$ clj number_parsing.clj
1.234
123
456
789
135
For input string: "wat"

Clojure’s number parsing is quite flexible and can handle various number formats without needing to specify the base explicitly in most cases. The read-string function automatically detects the appropriate number format.

Next, we’ll look at another common parsing task: URLs.