module Tins::Unit

def format(value, format: '%f %U', prefix: 1024, unit: ?b)

def format(value, format: '%f %U', prefix: 1024, unit: ?b)
  prefixes = prefixes(prefix)
  first_prefix = prefixes.first or
    raise ArgumentError, 'a non-empty array of prefixes is required'
  if value.zero?
    result = format.sub('%U', unit)
    result %= value
  else
    prefix = prefixes[
      (first_prefix.fraction ? -1 : 1) * Math.log(value.abs) / Math.log(first_prefix.step)
    ]
    result = format.sub('%U', "#{prefix.name}#{unit}")
    result %= (value / prefix.multiplier.to_f)
  end
end