Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a String to an Integer or Float in Crystal?

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?

like image 821
Ronan Boiteau Avatar asked Jul 13 '18 08:07

Ronan Boiteau


1 Answers

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.

like image 145
Ronan Boiteau Avatar answered Oct 15 '22 18:10

Ronan Boiteau