lib/si/module.rb in si-0.1.3 vs lib/si/module.rb in si-0.1.4

- old
+ new

@@ -15,11 +15,11 @@ PREFIXES.keys.sort.reverse.select { |exp| (min_exp..max_exp).include? exp }.each do |exp| denom = base ** exp if nump >= denom || exp == min_exp val = nump / denom - val = val.round [length - val.to_i.to_s.length, 0].max + val = SI.round val, [length - val.to_i.to_s.length, 0].max val = val.to_i if exp == 0 && num.is_a?(Fixnum) val = val.to_s.ljust(length + 1, '0') if val.is_a?(Float) return "#{minus}#{val}#{PREFIXES[exp]}" end @@ -27,16 +27,28 @@ nil end def revert str, options = {} - options = DEFAULT.select { |k, v| k == :base }.merge(options) - pair = PREFIXES.to_a.find { |k, v| v == str[-1] } + options = Hash[ DEFAULT.select { |k, v| k == :base } ].merge(options) + pair = PREFIXES.to_a.find { |k, v| !v.empty? && str =~ /[0-9]#{v}$/ } if pair str[0...-1].to_f * (options[:base] ** pair.first) else str.to_f + end + end + + if (RUBY_VERSION.split('.')[0, 2].map(&:to_i) <=> [1, 8]) == 1 + def round val, ndigits + val.round ndigits + end + else + def round val, ndigits + exp = (10 ** ndigits).to_f + val = ((val * exp).round / exp) + ndigits == 0 ? val.to_i : val end end end def si options = {}