How to work with leading zeros in integers

后端 未结 2 1916
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 05:08

What is the proper way to deal with leading zeros in Ruby?

0112.to_s
 => \"74\"
0112.to_i
 => 74

Why is it converting 0112

2条回答
  •  一生所求
    2020-12-10 06:01

    A numeric literal that starts with 0 is an octal representation, except the literals that start with 0x which represent hexadecimal numbers or 0b which represent binary numbers.

    1 * 8**2 + 1 * 8**1 + 2 * 8**0 == 74
    

    To convert it to 0112, use String#% or Kernel#sprintf with an appropriate format string:

    '0%o' % 0112  # 0: leading zero, %o: represent as an octal
    # => "0112"
    

提交回复
热议问题