Skip to content

Instantly share code, notes, and snippets.

@swanson
Created January 1, 2021 01:18
Show Gist options
  • Select an option

  • Save swanson/17710ba2a9c46570f24c66b971b7e6ce to your computer and use it in GitHub Desktop.

Select an option

Save swanson/17710ba2a9c46570f24c66b971b7e6ce to your computer and use it in GitHub Desktop.

Revisions

  1. matt swanson renamed this gist Jan 1, 2021. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. matt swanson created this gist Jan 1, 2021.
    25 changes: 25 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    # 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