Skip to content

Commit

Permalink
fixup! Add Number#humanize
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota committed Jul 3, 2018
1 parent 62d935d commit 544988a
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/number.cr
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ struct Number
end

# Default SI prefixes ordered by magnitude.
SI_PREFIXES = {nil, 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', nil, 'y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm'}
SI_PREFIXES = { {'y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm'}, {nil, 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'} }

# SI prefixes used by `#humanize`. Equal to `SI_PREFIXES` but prepends the
# prefix with a space charater.
Expand All @@ -244,10 +244,10 @@ struct Number
# ```
# Number.si_prefix(3) # => 'k'
# ```
def self.si_prefix(magnitude : Int) : Char?
max = SI_PREFIXES.size / 2
index = (magnitude / 3).clamp(-max..max)
SI_PREFIXES[index]
def self.si_prefix(magnitude : Int, prefixes = SI_PREFIXES) : Char?
index = (magnitude / 3)
prefixes = prefixes[magnitude < 0 ? 0 : 1]
prefixes[index.clamp((-prefixes.size + 1)..(prefixes.size - 1))]
end

# :nodoc:
Expand Down Expand Up @@ -285,9 +285,7 @@ struct Number
def humanize(io : IO, precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, prefixes : Indexable = SI_PREFIXES) : Nil
humanize(io, precision, separator, delimiter, base: base, significant: significant) do |magnitude, _|
magnitude = Number.prefix_index(magnitude)
max = prefixes.size / 2
index = (magnitude / 3).clamp(-max..max)
{magnitude, prefixes[index]}
{magnitude, Number.si_prefix(magnitude, prefixes)}
end
end

Expand Down

0 comments on commit 544988a

Please sign in to comment.