What's the easiest way to parse numbers in clojure?

后端 未结 10 1598
长发绾君心
长发绾君心 2020-12-08 09:30

I\'ve been using java to parse numbers, e.g.

(. Integer parseInt  numberString)

Is there a more clojuriffic way that would handle both int

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 09:59

    In my opinion the best/safest way that works when you want it to for any number and fails when it isn't a number is this:

    (defn parse-number
      "Reads a number from a string. Returns nil if not a number."
      [s]
      (if (re-find #"^-?\d+\.?\d*$" s)
        (read-string s)))
    

    e.g.

    (parse-number "43") ;=> 43
    (parse-number "72.02") ;=> 72.02
    (parse-number "009.0008") ;=> 9.008
    (parse-number "-92837482734982347.00789") ;=> -9.2837482734982352E16
    (parse-number "89blah") ;=> nil
    (parse-number "z29") ;=> nil
    (parse-number "(exploit-me)") ;=> nil
    

    Works for ints, floats/doubles, bignums, etc. If you wanted to add support for reading other notations, simply augment the regex.

提交回复
热议问题