Tintin81
Tintin81

Reputation: 10207

How to display integers as 6-digit values in Ruby on Rails?

How can I format integers in a text_field so that they always consist of 6 digits?

So for example when the integer is stored as 1 in the database, in the text_field it would say: 000001. The user should also be able to edit these values, yet not reduce or exceed the number of digits.

I tried something like this but it's not working for me:

def formatted_number(int)
  int.to_s.rjust(6, '0')
end

Thanks for any help.

Upvotes: 0

Views: 1173

Answers (1)

Patrick Oscity
Patrick Oscity

Reputation: 54684

Use string formatting:

def formatted_number(int)
  '%06d' % int
end

formatted_number(123)
#=> "000123"

For the sake of readability you can also use the explicit call to Kernel#format:

def formatted_number(int)
  format '%06d', int
end

Refer to the Kernel#format documentation for the syntax of the format string.

Upvotes: 4

Related Questions