How can I output leading zeros in Ruby?
If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do
str = "file_" + i.to_s.rjust(n, "0")
How to work with leading zeros in integers
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"
Leading zeros in 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 ofstr
, returns a newString
of lengthinteger
withstr
right justified and padded withpadstr
; otherwise, returnsstr
.
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'
Padding a number with zeros
puts 1.to_s.rjust(3, "0")
#=> 001
puts 10.to_s.rjust(3, "0")
#=> 010
puts 100.to_s.rjust(3, "0")
#=> 100
The above code would convert your user.id into a string, then String.rjust() method would consider its length and prefix appropriate number of zeros.
How do I insert leading zeros in Ruby dateTime minute
try
system["last_checkin"].to_time.strftime('%H:%M')
which will convert it to a Time(which has the date) and then you can use strftime to get the format you want
Ruby on Rails: How do you add add zeros in front of a number if it's under 10?
Did you mean sprintf '%02d', n
?
irb(main):003:0> sprintf '%02d', 1
=> "01"
irb(main):004:0> sprintf '%02d', 10
=> "10"
You might want to reference the format table for sprintf
in the future, but for this particular example '%02d'
means to print an integer (d
) taking up at least 2 characters (2
) and left-padding with zeros instead of spaces (0
).
Retain 0's when incrementing number
You can convert an integer to a String and give it a fixed amount of padding using String#rjust
, where the first argument is the total width of the resulting String, and the second argument is the character to use for padding:
>> int = 3
>> str = int.to_s.rjust(3, '0')
#=> "003"
And then you can increment that string using String#next
:
>> str.next
#=> "004"
Ruby: leading zeros with already formatted string
Because it was interpreted as an octal number.
Try it in irb:
> 0301
=> 193
But when you write:
> 301
=> 301
If you want to make it work, try to convert it to integer with String#to_i
:
"%06d" % s.to_i
sprintf("%06d", s.to_i)
Format a ruby decimal to string without leading zero (.123)
Solution
You can use :
format('%.3f', value).sub(/^0/, '')
It removes the first character if it is a 0 followed by a dot.
Test
values = [
0.725,
1.5,
0.125,
2.4567,
0,
10
]
values.each do |value|
p format('%.3f', value).sub(/^0/, '')
end
#=>
# ".725"
# "1.500"
# ".125"
# "2.457"
# ".000"
# "10.000"
Related Topics
How to Make the Days of the Month Be Printed According to Each Day (Ex: Su Mo Tu We...Etc)
Rails: Logging the Entire Stack Trace of an Exception
Pass Ruby Script File to Rails Console
Heroku: Push Rejected, Failed to Compile Ruby App
Recurring Billing with Rails and Activemerchant: Best Practices, Pitfalls, Gotchas
Transfer Db from One Heroku App to Another Faster
Devise Password Reset from Rails Console
How to Initialize an Array in One Step Using Ruby
How to Seed the Production Database Using the Capistrano Gem
Use Variable in Parameter Ruby on Rails
Finding Parenthesis via Regular Expression
How to Get the Current Working Directory's Absolute Path from Irb
How to Upgrade My Ruby 1.9.2-P0 to the Latest Patch Level Using Rvm
Rspec Error 'Report_Activate_Error': Could Not Find Rubygem Rspec-Core (>=0) (Gem:Loaderror)
How to Add 'Each' Method to Ruby Object (Or Should I Extend Array)
How to Set an Expectancy on Should_Receive and Have It Execute the Original Code