如何将String转换为Crystal中的Integer或Float?

Ron*_*eau 2 type-conversion crystal-lang

在Crystal中,如何将a转换StringIntegerFloat

使用Python我可以简单地执行以下操作:

>>> nb = "123"
>>> int(nb)
123
>>> nb = "1.23"
>>> float(nb)
1.23
Run Code Online (Sandbox Code Playgroud)

Crystal中有类似的工具吗?

Ron*_*eau 6

您可以使用String#to_iString#to_f方法:

"123".to_i # => 123

"1.23".to_f # => 1.23
Run Code Online (Sandbox Code Playgroud)