English 中文(简体)
如何将数字字符串转换为数字(十进制)和数字转换为字符串
原标题:How to convert a numeric string to number (decimal) and number to string

要将小数数字符串转换为小数数和小数数数转换为字符串,我如何着手写入函数?

最佳回答

此示例将数字字符串转换为数字。

(defn String->Number [str]
  (let [n (read-string str)]
       (if (number? n) n nil)))

样本 :

user=> (String->Number "4.5")
4.5
user=> (str 4.5)
"4.5"
user=> (String->Number "abc")
nil
问题回答

从任何东西转换为字符串,从类似于数字的字符串转换为“大十进制”功能非常方便:

user=> (bigdec "1234")
1234M
user=> (str 1234M)
"1234"

我想这是阴道的金刚石法

注意 read-string 给您一个浮点数, 而不是小数点数 :

user=> (.getClass (read-string "1.01"))
java.lang.Double

你拿回的指纹 和你想要的一样 但它不是 确切的说

user=> (new BigDecimal (read-string "1.01"))
1.0100000000000000088817841970012523233890533447265625M

您可以使用 java.math.BigDecimal 替代,避免浮点并发症:

user=> (new BigDecimal "1.01")
1.01M
user=> (.toString (new BigDecimal "1.01"))
"1.01"

从您的问题中,您似乎想要一个切换函数, 即可以读取一个数字, 转换为字符串, 也可以在字符串中读取并返回一个数字, 如果字符串包含数字数字数字, 如 123.0 或 “ 123.0 ” 。

以下是一个例子:

(defn cvt-str-num [val]
    (if (try 
            (number? val)
            (catch Exception e (str "Invalid number: " (.getMessage e))))
        (str val)
        (let [n-val (read-string val)]
            (if (number? n-val)
                n-val
                nil))))

我看不到什么方法可以绕过 nval 的绑定, 因为存储读字符串返回值需要一个临时位置, 这样它就可以被测试为一个数字。 如果它是数字, 它会返回; 其它的则返回零 。





相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签