Reputation: 4378
I got some weired problem while converting data type in ruby.
Here are some of the outputs that i got in console
0123 and enter gave me output 83
12345600.to_s #=> "12345600"
but
012345600.to_s gave me #=> "2739072" but i expect "012345600"
Seems like when there is 0 at the beginning of number the output is not as expected.
Can any one explain why this is happening? or provide me a solution so that i can get my expected output.
Thanks
Upvotes: 2
Views: 1353
Reputation: 81480
"Numbers" like a phone number 02555555555
aren't numbers at all. They're merely strings that only contain digits in them.
Upvotes: 0
Reputation: 83680
You can't return zero, but you can do this.
0123.to_s(8)
#=> "123"
Actually I am interested in how did you get such numbers like 0123?
Upvotes: 0
Reputation: 28554
Starting a number with a zero in Ruby is telling the parser that you are going to write the number in octal notation. Heres another SO with some info:
How do I convert an octal number to decimal in Ruby?
Upvotes: 2
Reputation: 10655
Having a 0 at the start of a number makes the interpreter/compiler interpret the following digits as an octal number sequence (base 8) not a decimal number sequence (base 10). Therefore the number you entered is an octal number and not decimal.
You can test this on a scientific calculator by putting it into octal mode and then switching to decimal.
Upvotes: 5