How to convert a String to an Integer or Float in Crystal?
Asked Answered
B

1

13

In Crystal, how can I convert a String to an Integer or Float?

Using Python I can simply do the following:

>>> nb = "123"
>>> int(nb)
123
>>> nb = "1.23"
>>> float(nb)
1.23

Are there any similar tools in Crystal?

Balbriggan answered 13/7, 2018 at 8:1 Comment(0)
B
14

You can use the String#to_i and String#to_f methods:

"123".to_i # => 123

"123".to_i64 # => 123 as Int64

"1.23".to_f # => 1.23

"1.23".to_f64 # => 1.23 as Float64

etc.

Balbriggan answered 13/7, 2018 at 8:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.