gentooboontoo / js-quantities

JavaScript library for quantity calculation and unit conversion
http://gentooboontoo.github.io/js-quantities/
MIT License
396 stars 102 forks source link

How to get the value converted to the "best" prefix? #87

Open alinex opened 7 years ago

alinex commented 7 years ago

I have a value of `1200000 mm' and I wan't to have a method which automatically transfers to the best prefix like:

const qty = new Qty(1200000, 'mm').toBest() // now set to 1.2, 'km'

Is this possible or how can I get the ordered list of units with prefixes for the given unit to do it myself?

adrfantini commented 9 months ago

My approach to this is to define all SI prefixes:

const SI_PREFIXES = [
  { u: 'y', s: 1e-24, lbl: 'yocto' },
  { u: 'z', s: 1e-21, lbl: 'zepto' },
  { u: 'a', s: 1e-18, lbl: 'atto' },
  { u: 'f', s: 1e-15, lbl: 'femto' },
  { u: 'p', s: 1e-12, lbl: 'pico' },
  { u: 'n', s: 1e-9, lbl: 'nano' },
  { u: '\u00B5', s: 1e-6, lbl: 'micro' },
  { u: 'm', s: 1e-3, lbl: 'milli' },
  { u: 'c', s: 1e-2, lbl: 'centi', ignoreToBest: true },
  { u: 'd', s: 1e-1, lbl: 'deci', ignoreToBest: true },
  { u: '', s: 1, lbl: '' }, // hack to also accept no SI prefix
  { u: 'da', s: 1e+1, lbl: 'deca', ignoreToBest: true },
  { u: 'h', s: 1e+2, lbl: 'hecto', ignoreToBest: true },
  { u: 'k', s: 1e+3, lbl: 'kilo' },
  { u: 'M', s: 1e+6, lbl: 'mega' },
  { u: 'G', s: 1e+9, lbl: 'giga' },
  { u: 'T', s: 1e+12, lbl: 'tera' },
  { u: 'P', s: 1e+15, lbl: 'peta' },
  { u: 'E', s: 1e+18, lbl: 'exa' },
  { u: 'Z', s: 1e+21, lbl: 'zetta' },
  { u: 'Y', s: 1e+24, lbl: 'yotta' },
  { u: 'googol', s: 1e+100, lbl: 'googol' }
];

Then I extended the Qty class with a toBest method which strips all SI units, converts to SI prefix + unit starting from SI_PREFIXES[0] and stops as soon as .scalar is smaller than a threshold (default = 1000).

This ensures a human-readable output. It works pretty well. It is the same thing that is done by convert-units and other similar libs.

If there is interest I can provide an example.