# Tutorial by Examples

## Casting to a String

123.5.to_s #=&gt; &quot;123.5&quot; String(123.5) #=&gt; &quot;123.5&quot; Usually, String() will just call #to_s. Methods Kernel#sprintf and String#% behave similar to C: sprintf(&quot;%s&quot;, 123.5) #=&gt; &quot;123.5&quot; &quot;%s&quot; % 123.5 #=&gt; &quot;123.5&quot; &quot;%d&quot...

## Casting to an Integer

&quot;123.50&quot;.to_i #=&gt; 123 Integer(&quot;123.50&quot;) #=&gt; 123 A string will take the value of any integer at its start, but will not take integers from anywhere else: &quot;123-foo&quot;.to_i # =&gt; 123 &quot;foo-123&quot;.to_i # =&gt; 0 However, there is a difference when ...

## Casting to a Float

&quot;123.50&quot;.to_f #=&gt; 123.5 Float(&quot;123.50&quot;) #=&gt; 123.5 However, there is a difference when the string is not a valid Float: &quot;something&quot;.to_f #=&gt; 0.0 Float(&quot;something&quot;) # ArgumentError: invalid value for Float(): &quot;something&quot;

## Floats and Integers

1/2 #=&gt; 0 Since we are dividing two integers, the result is an integer. To solve this problem, we need to cast at least one of those to Float: 1.0 / 2 #=&gt; 0.5 1.to_f / 2 #=&gt; 0.5 1 / Float(2) #=&gt; 0.5 Alternatively, fdiv may be used to return the floating point result of di...

Page 1 of 1