Giter Site home page Giter Site logo

gentooboontoo / js-quantities Goto Github PK

View Code? Open in Web Editor NEW
395.0 22.0 102.0 1.85 MB

JavaScript library for quantity calculation and unit conversion

Home Page: http://gentooboontoo.github.io/js-quantities/

License: MIT License

Ruby 0.09% HTML 0.19% JavaScript 99.35% Shell 0.18% Makefile 0.19%
javascript units measure temperature quantity quantities conversion physical measurement unit

js-quantities's Introduction

JS-quantities

Build Status

JS-quantities is originally a JavaScript port of Kevin Olbrich's library Ruby Units (http://github.com/olbrich/ruby-units).

The library aims to simplify the handling of units for scientific calculations involving quantities.

JS-quantities is built as UMD and ES modules and can be used with Node.js and browsers. It has no dependencies.

Installation

Install with npm install js-quantities or download latest release v1.8.0 as:

Usage

Node.js

// As CommonJS module
const Qty = require('js-quantities');

// As ES module
import Qty from 'js-quantities';

Browsers

  • UMD module could be included as is:
<script src='quantities.js'></script>

In this case, it will define a global variable Qty.

define(['quantities'], function(Qty) {
  ...
});
  • As ES module:
<script type="module">
  import Qty from "./path/to/quantities.mjs";
  // ...
</script>

Synopsis

Creation

Instances of quantities are made by means of Qty() method. Qty can both be used as a constructor (with new) or as a factory (without new):

qty = new Qty('23 ft'); // constructor
qty = Qty('23 ft'); // factory

Qty constructor accepts strings, numbers and Qty instances as initializing values.

If scalars and their respective units are available programmatically, the two argument signature may be useful:

qty = new Qty(124, 'cm'); // => 1.24 meter
qty = Qty(124, 'cm'); // => 1.24 meter

For the sake of simplicity, one will use the factory way below but using new Qty() is equivalent.

qty = Qty('1m'); // => 1 meter
qty = Qty('m'); // =>  1 meter (scalar defaults to 1)

qty = Qty('1 N*m');
qty = Qty('1 N m'); // * is optional

qty = Qty('1 m/s');

qty = Qty('1 m^2/s^2');
qty = Qty('1 m^2 s^-2'); // negative powers
qty = Qty('1 m2 s-2'); // ^ is optional

qty = Qty('1 m^2 kg^2 J^2/s^2 A');

qty = Qty('1.5'); // unitless quantity
qty = Qty(1.5); // number as initializing value

qty = Qty('1 attoparsec/microfortnight');

qtyCopy = Qty(qty); // quantity could be copied when used as
                    // initializing value

Qty.parse utility method is also provided to parse and create quantities from strings. Unlike the constructor, it will return null instead of throwing an error when parsing an invalid quantity.

Qty.parse('1 m'); // => 1 meter
Qty.parse('foo') // => null

Available well-known kinds

Qty.getKinds(); // => Array of names of every well-known kind of units

Available units of a particular kind

Qty.getUnits('currency'); // => [ 'dollar', 'cents' ]
// Or all alphabetically sorted
Qty.getUnits(); // => [ 'acre','Ah','ampere','AMU','angstrom']

Alternative names of a unit

Qty.getAliases('m'); // => [ 'm', 'meter', 'meters', 'metre', 'metres' ]

Quantity compatibility, kind and various queries

qty1.isCompatible(qty2); // => true or false

qty.kind(); // => 'length', 'area', etc...

qty.isUnitless(); // => true or false
qty.isBase(); // => true if quantity is represented with base units

Conversion

qty.toBase(); // converts to SI units (10 cm => 0.1 m) (new instance)

qty.toFloat(); // returns scalar of unitless quantity
               // (otherwise throws error)

qty.to('m'); // converts quantity to meter if compatible
             // or throws an error (new instance)
qty1.to(qty2); // converts quantity to same unit of qty2 if compatible
               // or throws an error (new instance)

qty.inverse(); // converts quantity to its inverse
               // ('100 m/s' => '.01 s/m')
// Inverses can be used, but there is no special checking to
// rename the units
Qty('10ohm').inverse() // '.1/ohm'
                       // (not '.1S', although they are equivalent)
// however, the 'to' command will convert between inverses also
Qty('10ohm').to('S') // '.1S'

Qty.swiftConverter() is a fast way to efficiently convert large array of Number values. It configures a function accepting a value or an array of Number values to convert.

var convert = Qty.swiftConverter('m/h', 'ft/s'); // Configures converter

// Converting single value
var converted = convert(2500); // => 2.278..

// Converting large array of values
var convertedSerie = convert([2500, 5000, ...]); // => [2.278.., 4.556.., ...]

The main drawback of this conversion method is that it does not take care of rounding issues.

Comparison

qty1.eq(qty2); // => true if both quantities are equal (1m == 100cm => true)
qty1.same(qty2); // => true if both quantities are same (1m == 100cm => false)
qty1.lt(qty2); // => true if qty1 is stricty less than qty2
qty1.lte(qty2); // => true if qty1 is less than or equal to qty2
qty1.gt(qty2); // => true if qty1 is stricty greater than qty2
qty1.gte(qty2); // => true if qty1 is greater than or equal to qty2

qty1.compareTo(qty2); // => -1 if qty1 < qty2,
                      // => 0 if qty1 == qty2,
                      // => 1 if qty1 > qty2

Operators

  • add(other): Add. other can be string or quantity. other should be unit compatible.
  • sub(other): Substract. other can be string or quantity. other should be unit compatible.
  • mul(other): Multiply. other can be string, number or quantity.
  • div(other): Divide. other can be string, number or quantity.

Rounding

Qty#toPrec(precision) : returns the nearest multiple of quantity passed as precision.

var qty = Qty('5.17 ft');
qty.toPrec('ft'); // => 5 ft
qty.toPrec('0.5 ft'); // => 5 ft
qty.toPrec('0.25 ft'); // => 5.25 ft
qty.toPrec('0.1 ft'); // => 5.2 ft
qty.toPrec('0.05 ft'); // => 5.15 ft
qty.toPrec('0.01 ft'); // => 5.17 ft
qty.toPrec('0.00001 ft'); // => 5.17 ft
qty.toPrec('2 ft'); // => 6 ft
qty.toPrec('2'); // => 6 ft

var qty = Qty('6.3782 m');
qty.toPrec('dm'); // => 6.4 m
qty.toPrec('cm'); // => 6.38 m
qty.toPrec('mm'); // => 6.378 m
qty.toPrec('5 cm'); // => 6.4 m
qty.toPrec('10 m'); // => 10 m
qty.toPrec(0.1); // => 6.3 m

var qty = Qty('1.146 MPa');
qty.toPrec('0.1 bar'); // => 1.15 MPa

Formatting quantities

Qty#toString returns a string using the canonical form of the quantity (that is it could be seamlessly reparsed by Qty).

var qty = Qty('1.146 MPa');
qty.toString(); // => '1.146 MPa'

As a shorthand, units could be passed to Qty#toString and is equivalent to successively call Qty#to then Qty#toString.

var qty = Qty('1.146 MPa');
qty.toString('bar'); // => '11.46 bar'
qty.to('bar').toString(); // => '11.46 bar'

Qty#toString could also be used with any method from Qty to make some sort of formatting. For instance, one could use Qty#toPrec to fix the maximum number of decimals:

var qty = Qty('1.146 MPa');
qty.toPrec(0.1).toString(); // => '1.1 MPa'
qty.to('bar').toPrec(0.1).toString(); // => '11.5 bar'

For advanced formatting needs as localization, specific rounding or any other custom customization, quantities can be transformed into strings through Qty#format according to optional target units and formatter. If target units are specified, the quantity is converted into them before formatting.

Such a string is not intended to be reparsed to construct a new instance of Qty (unlike output of Qty#toString).

If no formatter is specified, quantities are formatted according to default js-quantities' formatter and is equivalent to Qty#toString.

var qty = Qty('1.1234 m');
qty.format(); // same units, default formatter => '1.234 m'
qty.format('cm'); // converted to 'cm', default formatter => '123.45 cm'

Qty#format could delegates formatting to a custom formatter if required. A formatter is a callback function accepting scalar and units as parameters and returning a formatted string representing the quantity.

var configurableRoundingFormatter = function(maxDecimals) {
  return function(scalar, units) {
    var pow = Math.pow(10, maxDecimals);
    var rounded = Math.round(scalar * pow) / pow;

    return rounded + ' ' + units;
  };
};

var qty = Qty('1.1234 m');

// same units, custom formatter => '1.12 m'
qty.format(configurableRoundingFormatter(2));

// convert to 'cm', custom formatter => '123.4 cm'
qty.format('cm', configurableRoundingFormatter(1));

Custom formatter can be configured globally by setting Qty.formatter.

Qty.formatter = configurableRoundingFormatter(2);
var qty = Qty('1.1234 m');
qty.format(); // same units, current default formatter => '1.12 m'

Temperatures

Like ruby-units, JS-quantities makes a distinction between a temperature (which technically is a property) and degrees of temperature (which temperatures are measured in).

Temperature units (i.e., 'tempK') can be converted back and forth, and will take into account the differences in the zero points of the various scales. Differential temperature (e.g., '100 degC') units behave like most other units.

Qty('37 tempC').to('tempF') // => 98.6 tempF

JS-quantities will throw an error if you attempt to create a temperature unit that would fall below absolute zero.

Unit math on temperatures is fairly limited.

Qty('100 tempC').add('10 degC')  // 110 tempC
Qty('100 tempC').sub('10 degC')  // 90 tempC
Qty('100 tempC').add('50 tempC') // throws error
Qty('100 tempC').sub('50 tempC') // 50 degC
Qty('50 tempC').sub('100 tempC') // -50 degC
Qty('100 tempC').mul(scalar)     // 100*scalar tempC
Qty('100 tempC').div(scalar)     // 100/scalar tempC
Qty('100 tempC').mul(qty)        // throws error
Qty('100 tempC').div(qty)        // throws error
Qty('100 tempC*unit')            // throws error
Qty('100 tempC/unit')            // throws error
Qty('100 unit/tempC')            // throws error
Qty('100 tempC').inverse()       // throws error
Qty('100 tempC').to('degC') // => 100 degC

This conversion references the 0 point on the scale of the temperature unit

Qty('100 degC').to('tempC') // => -173.15 tempC

These conversions are always interpreted as being relative to absolute zero. Conversions are probably better done like this...

Qty('0 tempC').add('100 degC') // => 100 tempC

Errors

Every error thrown by JS-quantities is an instance of Qty.Error.

try {
  // code triggering an error inside JS-quantities
}
catch(e) {
  if(e instanceof Qty.Error) {
    // ...
  }
  else {
    // ...
  }
}

Tests

Tests are implemented with Jasmine (https://github.com/pivotal/jasmine). You could use both HTML and jasmine-node runners.

To execute specs through HTML runner, just open SpecRunner.html file in a browser to execute them.

To execute specs through jasmine-node, launch:

make test

Performance regression test

There is a small benchmarking HTML page to spot performance regression between currently checked-out quantities.js and any committed version. Just execute:

make bench

then open http://0.0.0.0:3000/bench

Checked-out version is benchmarked against HEAD by default but it could be changed by passing any commit SHA on the command line. Port (default 3000) is also configurable.

make bench COMMIT=e0c7fc468 PORT=5000

TypeScript type declarations

A TypeScript declaration file is published on DefinitelyTyped.

It could be installed with npm install @types/js-quantities.

Contribute

Feedback and contributions are welcomed.

Pull requests must pass tests and linting. Please make sure that make test and make lint return no errors before submitting.

js-quantities's People

Contributors

adridavid avatar benasradzeviciusdevbridge avatar beradrian avatar bombledmonk avatar bryant1410 avatar cheung31 avatar chris-cunningham avatar christianp avatar cjroth avatar dubejf avatar flyorboom avatar gentooboontoo avatar glepretre avatar jan-san avatar joshrickert avatar librilex avatar limrv avatar lukelaws avatar maasencioh avatar mickeyreiss avatar n8th8n8el avatar nayar avatar nickoveracker avatar nwesterman avatar rjanicek avatar robinovitch61 avatar sheam avatar trodi avatar vsmalladi avatar zbjornson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-quantities's Issues

Publish new version to NPM (current v1.5.0)

Can new version be published to NPM?

There are new functions that we would like to use that are not in current (1.5.0) NPM package (e.g. Qty.getUnits()). Thanks! Great work!

Return full human readable names

Great library! I'm just not sure if it's possible to get the full name of the unit from looking at the docs and code. e.g. I want to turn "m" into "meters".

Out-of-memory crash

This is a pathological case and it should return null, but this causes a "heap out of memory" error:

Qty.parse("58261da44b642352442b8060")

because this loop attempts to make a string of 64,235,244 repetitions of "4b " (i.e. 192 MB):

      // in var parse = function(val) {
      for (var i = 0; i < Math.abs(n) ; i++) {
        nx += x;
      }

I'm not exactly sure what that loop is supposed to be doing. Should n be clamped to the length of the input, or some hard-coded default?

Quantities with 'NaN' scalar

I noticed an unexpected behavior when trying to instantiate quantities directly from user input.

I know the correct way to instantiate a negative quantity is, for example:

var negativeQty = new Qty('-1 m');

This returns a perfectly valid qty:

{
  scalar: -1,
  baseScalar: -1,
  signature: 1,
  _conversionCache: {},
  numerator: [
    "<meter>"
  ],
  denominator: [
    "<1>"
  ],
  initValue": "-1 m",
  _isBase": true
}

But, these strings return qty objects with NaN scalar:

new Qty('- 1 m'); // .toString() --> "NaN *1*1*m"
new Qty('+ 1 m'); // .toString() --> "NaN *1*1*m"
new Qty('- m');   // .toString() --> "NaN m"
new Qty('+ m');   // .toString() --> "NaN m"

This is the object returned by "- 1 m":

{
  scalar: NaN,
  baseScalar: NaN,
  signature: 1,
  _conversionCache: {},
  numerator: [
    "<1>",
    "<meter>"
  ],
  denominator: [
    "<1>"
  ],
  initValue: "- 1 m",
  _isBase: true
}

Use case:
Users with no scientific or programming background are more likely to write "- 1 m" as input.

This is easy to handle in our client apps but the question is: should Qty return quantities with NaN scalar? I would rather expect it to return a valid qty or an Error.

Access to unit list

Hi, I'm using this awesome library for a project and although there exist a way to get the "well-known kinds" it is useless to me without having a way to obtain the unit list in that category (to put in a select widget or something), the code already has the list, it is just a matter of exposing it and maybe filtering it.

Thoughts?

'1 Mohm' interpreted as 'molar ohm'

In electronic engineering 1Mohm is typically 1000,000 Ohm.

> Qty = require('js-quantities')
> k = Qty('1kohm')
Qty {
  scalar: 1,
  baseScalar: 1000,
  signature: -312058,
  _conversionCache: {},
  numerator: [ '<kilo>', '<ohm>' ],
  denominator: [ '<1>' ],
  initValue: '1kohm',
  _isBase: false,
  _units: 'kOhm' }
> m = Qty('1Mohm')
Qty {
  scalar: 1,
  baseScalar: 1000,
  signature: 2887939,
  _conversionCache: {},
  numerator: [ '<molar>', '<ohm>' ],
  denominator: [ '<1>' ],
  initValue: '1Mohm',
  _isBase: false,
  _units: 'M*Ohm' }
> k.eq(m)
Error: Incompatible units
    at QtyError.Error (native)
    at new QtyError (./node_modules/js-quantities/src/quantities.js:1954:17)
    at throwIncompatibleUnits (./node_modules/js-quantities/src/quantities.js:764:11)
    at Qty.compareTo (./node_modules/js-quantities/src/quantities.js:1037:9)
    at Qty.eq (./node_modules/js-quantities/src/quantities.js:890:19)
    at repl:1:3
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:96:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:313:29)

Additionally it would be great to be able to space things like 1k ohm. Super nice bonus would be to be able to use EE convention of putting the quantifier instead of the decimal e.g. 1k5 ohm.

"force" is defined incorrectly.

Since Force is kg m/s^2, and

mass: 8000
length: 1
time: 20

We should have force: 8000+1-40 = 7961

However, in "kinds", force is incorrectly described with the identifier 7981. So, a N_s will be described as a force if you use Qty('1 N_s').kind()

TypeScript typings

Do you have any plans to create TypeScript type definitions for this package?

Add aliases to fluid ounces

I have a lot of data coming in formatted as 'fl oz', but it's not supported with the space so I have to do some custom parsing before handing it off to this library. Would be handy to support the spaced variants of fluid ounces: 'fl oz', 'fluid ounce', 'fluid ounces'.

Break into separate modules

It would be very useful for those of us doing client-side development if js-quantities could be split into a number of smaller CommonJS modules, so if only a few features are used the full library doesn't need to be compiled into an app bundle. As it stands, for the byte counter the library is a bit on the large size and offers many features that any single use case wouldn't need.

numerator and denominator getters to return a Qty object

Currently it seems .numerator and .denominator are used internally for consistency checking. However it would be useful to easily have access to the units of the numerator or denominator.

My particular use case is dealing with rates (unit/time). Ideally this is what I'd like to do:

var dt = Qty('1 hour');
var rate = Qty('1 kg/day');
var amount = rate.mul(dt).to(q.numeratorUnit);

I want to see how many kg I get in one hour. In general, if I define a rate of any kind, and I want to integrate it over some time interval by multiplying a time unit, I want to get back the units of the numerator. Note that the .to(...) is necessary because otherwise the units in this case will be unreduced: kg * hour / day

The best solution I've come up with came from poking around in the internals:

var dt = Qty('1 hour');
var rate = Qty('1 kg/day');
var numeratorUnit = Qty({scalar: 1, numerator: a.numerator});
var amount = rate.mul(dt).to();

This gets me the units of kg that I want.

Even if there were a getter for numerator that just returned the stringified unit name instead of the array [ '<kg>' ], that would make it much easier to work with. I know it's a nitpicky request but I wonder if there's any way to do this, or any other plans that would make this possible.

BTW, is there a simplify() or reduceUnits() function that would realize that day and hour are of the same dimension and scale the value accordingly?

Incorrect tablespoon conversion

Why does this conversion output 44 g?

var qtyunit = '3 tb';
qtyunit = Qty(qtyunit);
qtyunit = qtyunit.to('ml').toPrec('ml').toString();

Suggestion: toJSON() transport option

To persist a Qty object to a JSON store or pass to a JSON REST service it looks like you can rely on Qty#toString() roundtripping. However, it might be useful to have a Qty#toJSON() method (and a constructor/factory to match) that can serialize a richer data structure and potentially avoid some of the string generation and parsing steps.

Fails to parse mAh (milliamp hours)

The function fails to parse units of amp hours or milliamp hours.
Qty('1 Ah'); //exception QtyError: Unit not recognized
Qty.parse('1 Ah') // null

I haven't quite dissected where it is failing as my experience with the library is minimal. It may be that the units are incompatible as is, but I'm not sure yet, nor as to the reason why.

Qty('1 A h') parses to "1 A*h" which is certainly satisfactory, but can someone with a bit deeper knowledge elaborate on why the title values do not work?

Display in baseScalar units without changing to SI units

This may be easy, but I haven't quite teased out if this is possible yet.

Goal: I have data that comes in various magnitudes and I would like to normalize the the string output to the baseScalar while retuning the baseScalar's original label with the appropriate prefix change. The units are not known ahead of time so a simple someqty.to() seems to be out.

Example :
input = [1 mW, 1 W, 433 mW, 8 W]
desired output = [0.001 W, 1 W, 0.433 W, 8 W]

someqty.toBase() offers the baseScalar number, but it changes the units to SI representation. This works well for seconds and meters, but the representation of 100mW ends up being 0.1 kg*m2/s3.

One can just call someqty.baseScalar for the value, but how does one get the baseScalar's unit without transforming the label into something that is purely si units?

Am I think about this wrong? Is there a decent method converting the base scalar with only a simple prefix change on the output.

Unrecognized symbols cmH2O and inH2O

Hi, I was testing some all the units of some measurements and found some symbols that didn't work.

  • the symbols "cmH2O" and "inH2O" (pressure units) are not recognized
  • when using the grain symbol "gr" to any mass unit an incompatible unit exception is thrown

Provide a way to know the currently running version

This is an enhancement suggestion 😉

As I don't always remember all our dependencies versions,
I like libraries that provide a way to get it, for example:

angular.version
Object {full: "1.3.0", major: 1, minor: 3, dot: 0, codeName: "superluminal-nudge"}

Then this information can be useful to know if a recent feature or fix is available.

Infinite loop

When calling Qty.Parse('0.11 180°/sec'), the method never returns (I'm guessing an infinite loop).
I would expect it to return null.
If I change the number or remove the ° symbol it returns null as expected.

Problems with using js-quantities to parse engineering input

I'm trying to use js-quantities to parse input for an engineering simulation. I want users to enter input in any units by writing both the unit value and name. Ex, for a weight field, all of these would be acceptable:

160 kg
40 lbs
200 pound
14 microgram

This works by doing: (new Qty(element.val())).to("kg").scalar!

However, I have problems with a few other fields in my app:

Torque

While torque is supported, as it has the same dimension as energy, js-quantities will accept units of energy in a torque field. Additionally, while the dimension of lb ft is technically incorrect, torque is often expressed in these units (just look at any american automotive brochure)

new Qty('12 W h').to('N m').scalar;
43200

new Qty('278 lb ft').to('N m').scalar; //copied input string from ford.com
"Incompatible units"

Namespace collisions

The temperature field should naturally support the units C, F and K. Because of namespace collisions with farads and coulombs, temperature units are prepended with "temp", ie "tempC". This is not intuitive. Additionally, js-quantities will convert a temperature difference to an absolute temperature without error:

new Qty('12 degC').to('tempC').scalar;
-261.15

This is problematic, because to a user, "degC" actually sounds more correct than "tempC" because the common phrase is "degrees celsius". Ideally, valid inputs would include:

14.5 C
88 F
321 K

Derived unit parsing

Derived units require spaces between their components. This is not intuitive.

new Qty('12 kWh').to('J').scalar;
"Unit not recognized"

new Qty('12 Ah').to('C').scalar;
"Unit not recognized"

Conclusions

All of these problems stem from js-quantities not accepting any context about what unit it's trying to parse. This seems to suggest I am using this library for something it was not intended to do. I thought I'd post these gripes here because @gentooboontoo recently commented on a stackoverflow question, but I don't expect these to be fixed. I'm now looking at either finding another library or forking this one to make the changes I need.

Are the scalar and baseScalar properties public?

Hi,

The scalar and baseScalar properties aren't documented in the README.md, though there's a mention in a toFloat exception:

> q('10km').toFloat();
Error: Can't convert to Float unless unitless.  Use Unit#scalar`

Are theses properties public? If so the documentation might need to be updated.

Throw better errors

Adding a placeholder for updating errors thrown by js-quantities.

Preferably, an instance of Error should be thrown so users can handle them as they usually would other errors.

Additionally, it would be nice to have the args passed to the function printed as part of the message so that there is enough information in the message to be able to debug the issue.

If you agree, I'll send a pull request.

Thanks for the port, the library is great!

Cheers,
Jaap

ml and cc^3 are not being simplified

js-quantities doesn't simplify ml and cm^3 corrently when doing math.

var w = Qty('1 g');
var v = Qty('1 cm^3');
var density = w.div(v);
var sample_v = Qty('100 ml');
var sample_w = sample_v.mul(density);
sample_w.toString() // returns '100 ml*g/cm3', instead of '100 g'

js-quantities does recognize ml and cm^3 as the same unit however...

var q1 = Qty('1 cm^3');
var q2 = Qty('1 ml');
q1.eq(q2); // return true

Torque

There is currently no support for units of torque. Newton meters, pound feet, etc.

Publish to npm

Hey mate,

Thanks for all the work on this module.

Can you please update npm with v1.5.0? The version in npm doesn't contain the Qty.getKinds() method.

Issue with conversion from mmol/L to mg/dL.

mmol/l = mg/dl / 18
mg/dl = 18 × mmol/l

Trying to make a medical calculator with js-quantities. But can't seem to convert between the two frequently used units to measure blood sugar.

Anything I'm missing?

I tried - Qty.swiftConverter('mmol/l', 'mg/dl');

Results in : "QtyError", "Incompatible units"

Thanks in advance.

Unitless values with prefixes

Is it possible to use unitless values and convert them to their suffixes?
Like, for example: 1000 -> 1K, 1000K -> 1000M?

Cannot multiply 2 unit-less instances

Trivial example in Chrome dev console:

> var one=new Qty('1'), foot=new Qty('ft')
undefined
> one.toString()
"1"
> foot.toString()
"1 ft"
> (one.mul(foot)).toString()
"1 ft"
> (foot.mul(one)).toString()
"1 ft"
> (foot.mul(foot)).toString()
"1 ft2"
> (one.mul(one)).toString()
ERROR: "Unit not recognized"

The error comes from to() when other is unitless

"C" as Celsius recognized, but "°C" is not

It would be wonderful if the degree symbol was recognized as part of a temperature unit. Then, there would be no need to strip out the ° symbol when performing calculations or conversions.

Incompatibility exception doesn't report units

I get a QtyError about incompatible units in an addition operation, but it doesn't say what units are incompatible! I must deduce what units the operands have. Debugging would be faster if the exception object recorded and displayed this information.

Temperature conversion issue

The conversion between degC and degK or degF takes into account the multiplication factor but not the offset. 0 degC should be 273.15 degK or 32 degF.

Can you add a field to UNITS for offset?

Conversions for temp (degress C<->F<->K) wrong

The code:

"<kelvin>" : [["degK","kelvin"], 1.0, "temperature", ["<kelvin>"]],
 "<celsius>" : [["degC","celsius","celsius","centigrade"], 1.0, "temperature", ["<kelvin>"]],
 "<fahrenheit>" : [["degF","fahrenheit"], 1/1.8, "temperature", ["<kelvin>"]],

TempC = TempK - 273.15

E.g., 20 degC = 293.15 degK. Currently js-quantities converts 20degC to 20degK.

Same issue with degC to degF.... js-quantities converts 20degC to 36degF ..... it should be 68degF.

From firebug console:

qty1 = new Qty("20degC");
20 degC { scalar=20, base_scalar=20, unit_name="degC", more...}
qty1.to("degK");
20 degK { scalar=20, base_scalar=20, unit_name="degK", more...}
qty2 = new Qty("20degC");
20 degC { scalar=20, base_scalar=20, unit_name="degC", more...}
qty2.to("degF");
36 degF { scalar=36, base_scalar=20, unit_name="degF", more...}

Fix Qty#toPrec rounding

Reported by Adam Abrams:
new Qty('0.8 cu').toPrec('0.25 cu') returns 0.8 cu but should return 0.75 cu

Nonlinear units

Is there a plan to support nonlinear units? One example is gauge (AWG), which is a length (diameter) with a conversion: d (mm) = 0.127*92^((36-n)/39)

kWh unit

Hi

While testing I discovered that I cannot parse unit kWh. kW*h works just fine, but nobody is using this format. Is there a way to add this or have some kind of aliases?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.