Pregunta

is there a package available that does automatic unit conversion? Something that searches for the optimal unit for displaying purposes.

For example when I have the number 0.000001m it outputs 1 µm?
Or 0.000000001m to 1 nm

¿Fue útil?

Solución 2

Let's see what we can achieve with a simple recursive approach.

class Numeric
  def choose_best_scale(prefix = nil)
    if abs >= 1e2
      (self / 1e3).choose_best_scale next_prefix(prefix)
    elsif abs <= 1e-2
      (self * 1e3).choose_best_scale prev_prefix(prefix)
    else
      [self, prefix]
    end
  end

  private

  SIPrefixes = [:n, :μ, :m, :k, :M, :G]

  def prev_prefix(prefix)
    return :m if prefix.nil?
    SIPrefixes[SIPrefixes.index(prefix) - 1]
  end

  def next_prefix(prefix)
    return :k if prefix.nil?
    SIPrefixes[SIPrefixes.index(prefix) + 1]
  end
end

And here's how it works in practice.

pry(main)> (-6..6).map { |x| (10.0 ** x).choose_best_scale }
=> [[1.0, :μ],
    [10.0, :μ],
    [0.1, :m],
    [1.0, :m],
    [10.0, :m],
    [0.1, nil],
    [1.0, nil],
    [10.0, nil],
    [0.1, :k],
    [1.0, :k],
    [10.0, :k],
    [0.1, :M],
    [1.0, :M]]

Otros consejos

I am not sure though but maybe this will help

http://ruby-units.rubyforge.org/ruby-units/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top