1.9.3-p551 :016 > 00232.to_i
=> 154
1.9.3-p551 :017 > 0023.to_i
=> 19
1.9.3-p551 :024 > 23.to_i
=> 23
conversion of number with leading zeros to integer type gives undesirable results. Couldn't able to figure out the reason?. Please advise
1.9.3-p551 :016 > 00232.to_i
=> 154
1.9.3-p551 :017 > 0023.to_i
=> 19
1.9.3-p551 :024 > 23.to_i
=> 23
conversion of number with leading zeros to integer type gives undesirable results. Couldn't able to figure out the reason?. Please advise
Drop the initial zero as it is for representational purpose in Octal numbers.
> 00232.to_i
=> 154 # (2 * (8**0)) + (3 * (8**1)) + (2 * (8**2)) + (0 * (8**3))
# 2 + 24 + 128
# => 154
Similarly for others.
> 0023.to_i
=> 19 # (3 * (8**0)) + (2 * (8**1)) + (0 * (8**2))
# 3 + 16 + 0
# => 19
Ruby treats the number as octal(base 8) number if it has leading zeros.
To get the decimal number equivalent, convert it to string before converting it to integer.
023.to_s(8).to_i
=> 23