In Clojure how can I convert a String to a number?

前端 未结 13 655
别跟我提以往
别跟我提以往 2020-12-12 15:34

I have various strings, some like \"45\", some like \"45px\". How how I convert both of these to the number 45?

相关标签:
13条回答
  • 2020-12-12 16:12

    Expanding on snrobot's answer:

    (defn string->integer [s] 
      (when-let [d (re-find #"-?\d+" s)] (Integer. d)))
    

    This versions returns nil if there are no digits in the input, rather than raising an exception.

    My question is whether it's acceptable to abbreviate the name to "str->int", or if things like this should always be fully specified.

    0 讨论(0)
提交回复
热议问题