领先的零轨道

我在我的申请中有hrmin两个字段。 对于hr字段,如果用户input“1”,我希望Rails在将它保存到数据库之前自动将它填充到“01”。 对于min字段,如果用户input“0”,则应该input“00”。

我怎样才能做到这一点?

最好把它作为一个整数来存储,并且像在运行时描述的那样显示它。 每种语言都有自己的填充零的方法 – 对于Ruby,您可以使用String#rjust 。 此方法使用给定的填充字符填充string(右alignment),使其成为给定的长度。

str.rjust(integer, padstr=' ') → new_str

如果integer大于str的长度,则返回一个长度为integer的新String ,其中str右alignment并用padstr填充; 否则,返回str

 some_int = 5 some_int.to_s.rjust(2, '0') # => '05' some_int.to_s.rjust(5, '0') # => '00005' another_int = 150 another_int.to_s.rjust(2, '0') # => '150' another_int.to_s.rjust(3, '0') # => '150' another_int.to_s.rjust(5, '0') # => '00150' 

您可以将整数转换为这种types的string:

 result_string = '%02i' % your_integer 

这与它在数据库中的保存方式无关。

  • RDoc文档
  • 解释和例子

这也很方便:

 "%.2d" % integer 

结果string将是2个字符,如果数字小于2个字符,则string中将出现0

您不能将01存储为整数。 它将被转换为1

您可以将其存储为string,也可以将其显示为string“01”

我喜欢%操作符,即使它似乎已经失宠了…

 2.0.0-p247 :001 > '%02i' % 1 => "01" 2.0.0-p247 :002 > '%2i' % 1 => " 1" 2.0.0-p247 :003 > '%-2i' % 1 => "1 " 

另一种实现这一点的方法是使用sprintf在显示时间填充整数:

 f = sprintf '%04d', 49 # f = "0049" 

试试这个,你可以改变它们来匹配

 def numeric92(num) if num.present? if num < 0 && num > -1 ('-%05d' % num) + '.' + ('%.2f' % num).split('.').last else ('%06d' % num) + '.' + ('%.2f' % num).split('.').last end else '000000.00' end end