11

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?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56

1 Answers1

12

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.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56