开发者

Display a number in the style of Stackoverflow reputation

My reputation appears as 2,606.

What's the best way to display a number in this format using Ruby?


You can do with this simple method:

class Integer
  def pretty_str
    case
    when self < 1000
      to_s
    when self < 10000
      to_s.insert(1, ",")
    when self < 100000
      ("%.1fk" % (self / 1000.0)).sub(".0", "")
    else
      (self / 1000).pretty_str << "k"
    end
  end
end

123.pretty_str       #=> "123"
1234.pretty_str      #=> "1,234"
12345.pretty_str     #=> "12.3k"
123456.pretty_str    #=> "123k"
1234567.pretty_str   #=> "1.234k"
12345678.pretty_str  #=> "12.3kk"


I just installed ruby and this is my first attempt with the language. May be it's very un-rubyesque

def reputation(x)
  if x >= 100000
    "%dk" % (x / 1000)
  elsif x >= 10000
    "%.1fk" % (x / 1000.0)
  elsif x >= 1000
    "%d" % (x/1000) + ",%03d" % (x%1000)
  else
    "%d" % x
  end
end

puts reputation(999)    # --> 999
puts reputation(1000)   # --> 1,000
puts reputation(1234)   # --> 1,234
puts reputation(9999)   # --> 9,999
puts reputation(10000)  # --> 10.0k
puts reputation(12345)  # --> 12,3k
puts reputation(123456) # --> 123k

EDIT: Removed returns and added comma for thousands

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜