leading zeros in rails
RubyRegexRuby on-Rails-3Ruby Problem Overview
I have fields hr
and min
, both integers in my application. For hr
field, if the user enters "1" I would like Rails to automatically pad it to "01" before saving it to the database. Also for the min
field if the user enter "0" it should put in as "00".
How can I do this?
Ruby Solutions
Solution 1 - Ruby
It'd be better to store it as an integer and just display it as you described on runtime. Every language has its own way to pad zeros - for Ruby you can use String#rjust. This method pads a string (right-justified) so that it becomes a given length, using a given padding character.
> str.rjust(integer, padstr=' ') → new_str
>
> If integer
is greater than the length of str
, returns a new String
of length integer
with str
right justified and padded with padstr
; otherwise, returns 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'
Solution 2 - Ruby
You can transform the integer into a string of that kind with:
result_string = '%02i' % your_integer
This is independent from how it gets saved in the db.
Solution 3 - Ruby
This is also quite handy:
"%.2d" % integer
The resultant string will be of 2 characters and if the number is of less than 2 characters, then 0s will be present in the string
Solution 4 - Ruby
You can't store 01
as integer. It will be converted to 1
You can store it as a string, or you can show it as a string "01"
Solution 5 - Ruby
I like the % operator, even though it seems to have gone out of favor...
2.0.0-p247 :001 > '%02i' % 1
=> "01"
2.0.0-p247 :002 > '%2i' % 1
=> " 1"
2.0.0-p247 :003 > '%-2i' % 1
=> "1 "
Solution 6 - Ruby
Another way to achieve this is to pad your integer at display time, using sprintf:
f = sprintf '%04d', 49
# f = "0049"
Solution 7 - Ruby
Try this and you can change them to match
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