Ruby on Rails:如果数字小于 10,如何在数字前添加零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2692853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails: How do you add add zeros in front of a number if it's under 10?
提问by sjsc
I'm looking to convert single digit numbers to two-digit numbers like so:
我希望将一位数字转换为两位数字,如下所示:
9 ==> 09
5 ==> 05
12 == 12
4 ==> 04
I figure I could put a bunch of if-else statements (if number is under 10, then do a gsub) but figure that's horrible coding. I know Rails has number_with_precision but I see that it only applies to decimal numbers. Any ideas on how to convert single-digits to two-digits?
我想我可以放一堆 if-else 语句(如果数字小于 10,那么做一个 gsub)但我认为这是可怕的编码。我知道 Rails 有 number_with_precision,但我看到它只适用于十进制数。关于如何将个位数转换为两位数的任何想法?
回答by Ryan Bigg
A lot of people using sprintf(which is the right thing to do), and I think if you want to do this for a stringit's best to keep in mind the rjustand ljustmethods:
很多人都在使用sprintf(这是正确的做法),我认为如果您想对字符串执行此操作,最好记住rjust和ljust方法:
"4".rjust(2, '0')
This will make the "4"right justified by ensuring it's at least 2characters long and pad it with '0'. ljustdoes the opposite.
这将"4"通过确保它至少是2字符长并用'0'. ljust相反。
回答by Mark Rushakoff
Did you mean sprintf '%02d', n?
你的意思是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 sprintfin 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).
您可能希望在将来引用格式表sprintf,但对于此特定示例,这'%02d'意味着打印一个整数 ( d),该整数至少占 2 个字符 ( 2),并使用零而不是空格 ( 0)向左填充。
回答by ax.
回答by Salil
Try this, it should work:
试试这个,它应该可以工作:
abc= 5
puts "%.2i" %abc >> 05
abc= 5.0
puts "%.2f" %abc >> 5.00

