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

前端 未结 13 656
别跟我提以往
别跟我提以往 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 15:47

    This isn't perfect, but here's something with filter, Character/isDigit and Integer/parseInt. It won't work for floating point numbers and it fails if there is no digit in the input, so you should probably clean it up. I hope there's a nicer way of doing this that doesn't involve so much Java.

    user=> (defn strToInt [x] (Integer/parseInt (apply str (filter #(Character/isDigit %) x))))
    #'user/strToInt
    user=> (strToInt "45px")
    45
    user=> (strToInt "45")
    45
    user=> (strToInt "a")
    java.lang.NumberFormatException: For input string: "" (NO_SOURCE_FILE:0)
    

提交回复
热议问题