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

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

    The question asks about parsing a string into a number.

    (number? 0.5)
    ;;=> true
    

    So from the above decimals ought to be parsed as well.

    Perhaps not exactly answering the question now, but for general use I think you would want to be strict about whether it is a number or not (so "px" not allowed) and let the caller handle non-numbers by returning nil:

    (defn str->number [x]
      (when-let [num (re-matches #"-?\d+\.?\d*" x)]
        (try
          (Float/parseFloat num)
          (catch Exception _
            nil))))
    

    And if Floats are problematic for your domain instead of Float/parseFloat put bigdec or something else.

提交回复
热议问题