Skip to content

Instantly share code, notes, and snippets.

@samudary
Forked from swanson/helper.rb
Created January 1, 2021 15:05
Show Gist options
  • Save samudary/f381408720c0635225a32078facac561 to your computer and use it in GitHub Desktop.
Save samudary/f381408720c0635225a32078facac561 to your computer and use it in GitHub Desktop.
# Formats a +number+ into an abbreviated string suitable for
# displaying social media type metrics
#
# ==== Options
# * start_at - The first number to start abbreviating, defaults
# to 10_000. Certain metrics may want to start at e.g. 1000.
#
# ==== Examples
# number_to_social(123) # => 123
# number_to_social(1457) # => 1457
# number_to_social(9987) # => 9987
# number_to_social(10512) # => 10.5K
# number_to_social(2_300_123) # => 2.3M
# number_to_social(1457, start_at: 1000) # => 1.4K
def number_to_social(number, start_at: 10_000)
return number_with_delimiter(number) if number < start_at
number_to_human(number,
precision: 1,
round_mode: :down,
significant: false,
format: "%n%u",
units: { thousand: "K", million: "M", billion: "B" }
)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment