I am trying to pad zeros to a decimal result.
Is there a one-line code to do this in the view?
<%= "%00.1f" % (29/10.0) %>
expected: 02.9
the above returned: 2.9
I am trying to pad zeros to a decimal result.
Is there a one-line code to do this in the view?
<%= "%00.1f" % (29/10.0) %>
expected: 02.9
the above returned: 2.9
You could do
<%= ("%00.1f" % (29/10.0)).rjust(4, '0') %>
Which is basically saying if the result is less than four characters in length, add '0' to the left to bring it to the appropriate length.
If you plan to do this often, you might want to make a helper for this in your app/helpers/application_helper.rb
def my_format(value)
("%00.1f" % value).rjust(4, '0')
end
And then do
<%= my_format(29/10.0) %>
For those who want to pad zeroes to floating or decimal values, just provide the number of characters to be printed.
"%04.1f" % (29/10.0)
4 means four characters will be printed including the decimal and the decimal point.