{"id":19007413,"url":"https://github.com/gentooboontoo/js-quantities","last_synced_at":"2025-05-15T14:06:26.446Z","repository":{"id":411107,"uuid":"814830","full_name":"gentooboontoo/js-quantities","owner":"gentooboontoo","description":"JavaScript library for quantity calculation and unit conversion","archived":false,"fork":false,"pushed_at":"2024-03-25T19:52:08.000Z","size":1898,"stargazers_count":398,"open_issues_count":57,"forks_count":102,"subscribers_count":20,"default_branch":"master","last_synced_at":"2025-05-07T18:55:56.900Z","etag":null,"topics":["conversion","convert","imperial","javascript","measure","measurement","metric","parse","parser","physical","quantities","quantity","temperature","unit","units"],"latest_commit_sha":null,"homepage":"http://gentooboontoo.github.io/js-quantities/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gentooboontoo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2010-08-03T15:41:42.000Z","updated_at":"2025-04-14T16:45:43.000Z","dependencies_parsed_at":"2023-07-06T20:16:30.564Z","dependency_job_id":"524421f4-c07a-466e-9d8f-b23b58cda3c5","html_url":"https://github.com/gentooboontoo/js-quantities","commit_stats":{"total_commits":347,"total_committers":41,"mean_commits":8.463414634146341,"dds":0.6397694524495677,"last_synced_commit":"c0b81c25a120ffd64fe5a9577a39415cc45bdcea"},"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gentooboontoo%2Fjs-quantities","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gentooboontoo%2Fjs-quantities/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gentooboontoo%2Fjs-quantities/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gentooboontoo%2Fjs-quantities/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gentooboontoo","download_url":"https://codeload.github.com/gentooboontoo/js-quantities/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254355335,"owners_count":22057354,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["conversion","convert","imperial","javascript","measure","measurement","metric","parse","parser","physical","quantities","quantity","temperature","unit","units"],"created_at":"2024-11-08T18:38:19.073Z","updated_at":"2025-05-15T14:06:21.425Z","avatar_url":"https://github.com/gentooboontoo.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JS-quantities\n\n[![Build Status](https://travis-ci.org/gentooboontoo/js-quantities.png)](https://travis-ci.org/gentooboontoo/js-quantities)\n\nJS-quantities is originally a JavaScript port of Kevin Olbrich's library Ruby\nUnits (http://github.com/olbrich/ruby-units).\n\nThe library aims to simplify the handling of units for scientific calculations\ninvolving quantities.\n\nJS-quantities is built as UMD and ES modules and can be used with Node.js\nand browsers. It has **no dependencies**.\n\n## Installation\n\nInstall with `npm install js-quantities` or download latest release v1.8.0 as:\n\n* [UMD module](https://raw.github.com/gentooboontoo/js-quantities/v1.8.0/build/quantities.js)\n* [ES module](https://raw.github.com/gentooboontoo/js-quantities/v1.8.0/build/quantities.mjs)\n\n## Usage\n\n### Node.js\n\n```javascript\n// As CommonJS module\nconst Qty = require('js-quantities');\n\n// As ES module\nimport Qty from 'js-quantities';\n```\n\n### Browsers\n\n* UMD module could be included as is:\n\n```html\n\u003cscript src='quantities.js'\u003e\u003c/script\u003e\n```\n\nIn this case, it will define a global variable `Qty`.\n\n* With an AMD loader like [Require.JS](http://requirejs.org/):\n\n```javascript\ndefine(['quantities'], function(Qty) {\n  ...\n});\n```\n\n* As ES module:\n\n```html\n\u003cscript type=\"module\"\u003e\n  import Qty from \"./path/to/quantities.mjs\";\n  // ...\n\u003c/script\u003e\n```\n\n## Synopsis\n\n### Creation\n\nInstances of quantities are made by means of `Qty()` method. `Qty` can both be\nused as a constructor (with new) or as a factory (without new):\n\n```javascript\nqty = new Qty('23 ft'); // constructor\nqty = Qty('23 ft'); // factory\n```\n\n`Qty` constructor accepts strings, numbers and `Qty` instances as\ninitializing values.\n\nIf scalars and their respective units are available programmatically, the\ntwo argument signature may be useful:\n\n```javascript\nqty = new Qty(124, 'cm'); // =\u003e 1.24 meter\nqty = Qty(124, 'cm'); // =\u003e 1.24 meter\n```\n\nFor the sake of simplicity, one will use the factory way below but using\n`new Qty()` is equivalent.\n\n```javascript\nqty = Qty('1m'); // =\u003e 1 meter\nqty = Qty('m'); // =\u003e  1 meter (scalar defaults to 1)\n\nqty = Qty('1 N*m');\nqty = Qty('1 N m'); // * is optional\n\nqty = Qty('1 m/s');\n\nqty = Qty('1 m^2/s^2');\nqty = Qty('1 m^2 s^-2'); // negative powers\nqty = Qty('1 m2 s-2'); // ^ is optional\n\nqty = Qty('1 m^2 kg^2 J^2/s^2 A');\n\nqty = Qty('1.5'); // unitless quantity\nqty = Qty(1.5); // number as initializing value\n\nqty = Qty('1 attoparsec/microfortnight');\n\nqtyCopy = Qty(qty); // quantity could be copied when used as\n                    // initializing value\n```\n\n`Qty.parse` utility method is also provided to parse and create\nquantities from strings. Unlike the constructor, it will return `null`\ninstead of throwing an error when parsing an invalid quantity.\n\n```javascript\nQty.parse('1 m'); // =\u003e 1 meter\nQty.parse('foo') // =\u003e null\n```\n\n### Available well-known kinds\n\n```javascript\nQty.getKinds(); // =\u003e Array of names of every well-known kind of units\n```\n\n### Available units of a particular kind\n\n```javascript\nQty.getUnits('currency'); // =\u003e [ 'dollar', 'cents' ]\n// Or all alphabetically sorted\nQty.getUnits(); // =\u003e [ 'acre','Ah','ampere','AMU','angstrom']\n```\n\n### Alternative names of a unit\n\n```javascript\nQty.getAliases('m'); // =\u003e [ 'm', 'meter', 'meters', 'metre', 'metres' ]\n```\n\n### Quantity compatibility, kind and various queries\n\n```javascript\nqty1.isCompatible(qty2); // =\u003e true or false\n\nqty.kind(); // =\u003e 'length', 'area', etc...\n\nqty.isUnitless(); // =\u003e true or false\nqty.isBase(); // =\u003e true if quantity is represented with base units\n```\n\n### Conversion\n\n```javascript\nqty.toBase(); // converts to SI units (10 cm =\u003e 0.1 m) (new instance)\n\nqty.toFloat(); // returns scalar of unitless quantity\n               // (otherwise throws error)\n\nqty.to('m'); // converts quantity to meter if compatible\n             // or throws an error (new instance)\nqty1.to(qty2); // converts quantity to same unit of qty2 if compatible\n               // or throws an error (new instance)\n\nqty.inverse(); // converts quantity to its inverse\n               // ('100 m/s' =\u003e '.01 s/m')\n// Inverses can be used, but there is no special checking to\n// rename the units\nQty('10ohm').inverse() // '.1/ohm'\n                       // (not '.1S', although they are equivalent)\n// however, the 'to' command will convert between inverses also\nQty('10ohm').to('S') // '.1S'\n```\n\n`Qty.swiftConverter()` is a fast way to efficiently convert large array of\nNumber values. It configures a function accepting a value or an array of Number\nvalues to convert.\n\n```javascript\nvar convert = Qty.swiftConverter('m/h', 'ft/s'); // Configures converter\n\n// Converting single value\nvar converted = convert(2500); // =\u003e 2.278..\n\n// Converting large array of values\nvar convertedSerie = convert([2500, 5000, ...]); // =\u003e [2.278.., 4.556.., ...]\n```\n\nThe main drawback of this conversion method is that it does not take care of\nrounding issues.\n\n### Comparison\n\n```javascript\nqty1.eq(qty2); // =\u003e true if both quantities are equal (1m == 100cm =\u003e true)\nqty1.same(qty2); // =\u003e true if both quantities are same (1m == 100cm =\u003e false)\nqty1.lt(qty2); // =\u003e true if qty1 is stricty less than qty2\nqty1.lte(qty2); // =\u003e true if qty1 is less than or equal to qty2\nqty1.gt(qty2); // =\u003e true if qty1 is stricty greater than qty2\nqty1.gte(qty2); // =\u003e true if qty1 is greater than or equal to qty2\n\nqty1.compareTo(qty2); // =\u003e -1 if qty1 \u003c qty2,\n                      // =\u003e 0 if qty1 == qty2,\n                      // =\u003e 1 if qty1 \u003e qty2\n```\n\n### Operators\n\n* add(other): Add. other can be string or quantity. other should be unit compatible.\n* sub(other): Substract. other can be string or quantity. other should be unit compatible.\n* mul(other): Multiply. other can be string, number or quantity.\n* div(other): Divide. other can be string, number or quantity.\n\n### Rounding\n\n`Qty#toPrec(precision)` : returns the nearest multiple of quantity passed as\nprecision.\n\n```javascript\nvar qty = Qty('5.17 ft');\nqty.toPrec('ft'); // =\u003e 5 ft\nqty.toPrec('0.5 ft'); // =\u003e 5 ft\nqty.toPrec('0.25 ft'); // =\u003e 5.25 ft\nqty.toPrec('0.1 ft'); // =\u003e 5.2 ft\nqty.toPrec('0.05 ft'); // =\u003e 5.15 ft\nqty.toPrec('0.01 ft'); // =\u003e 5.17 ft\nqty.toPrec('0.00001 ft'); // =\u003e 5.17 ft\nqty.toPrec('2 ft'); // =\u003e 6 ft\nqty.toPrec('2'); // =\u003e 6 ft\n\nvar qty = Qty('6.3782 m');\nqty.toPrec('dm'); // =\u003e 6.4 m\nqty.toPrec('cm'); // =\u003e 6.38 m\nqty.toPrec('mm'); // =\u003e 6.378 m\nqty.toPrec('5 cm'); // =\u003e 6.4 m\nqty.toPrec('10 m'); // =\u003e 10 m\nqty.toPrec(0.1); // =\u003e 6.3 m\n\nvar qty = Qty('1.146 MPa');\nqty.toPrec('0.1 bar'); // =\u003e 1.15 MPa\n```\n\n### Formatting quantities\n\n`Qty#toString` returns a string using the canonical form of the quantity (that\nis it could be seamlessly reparsed by `Qty`).\n\n```javascript\nvar qty = Qty('1.146 MPa');\nqty.toString(); // =\u003e '1.146 MPa'\n```\n\nAs a shorthand, units could be passed to `Qty#toString` and is equivalent to\nsuccessively call `Qty#to` then `Qty#toString`.\n\n```javascript\nvar qty = Qty('1.146 MPa');\nqty.toString('bar'); // =\u003e '11.46 bar'\nqty.to('bar').toString(); // =\u003e '11.46 bar'\n```\n\n`Qty#toString` could also be used with any method from `Qty` to make some sort\nof formatting. For instance, one could use `Qty#toPrec` to fix the maximum\nnumber of decimals:\n\n```javascript\nvar qty = Qty('1.146 MPa');\nqty.toPrec(0.1).toString(); // =\u003e '1.1 MPa'\nqty.to('bar').toPrec(0.1).toString(); // =\u003e '11.5 bar'\n```\n\nFor advanced formatting needs as localization, specific rounding or any other\ncustom customization, quantities can be transformed into strings through\n`Qty#format` according to optional target units and formatter. If target units\nare specified, the quantity is converted into them before formatting.\n\nSuch a string is not intended to be reparsed to construct a new instance of\n`Qty` (unlike output of `Qty#toString`).\n\nIf no formatter is specified, quantities are formatted according to default\njs-quantities' formatter and is equivalent to `Qty#toString`.\n\n```javascript\nvar qty = Qty('1.1234 m');\nqty.format(); // same units, default formatter =\u003e '1.234 m'\nqty.format('cm'); // converted to 'cm', default formatter =\u003e '123.45 cm'\n```\n\n`Qty#format` could delegates formatting to a custom formatter if required. A\nformatter is a callback function accepting scalar and units as parameters and\nreturning a formatted string representing the quantity.\n\n```javascript\nvar configurableRoundingFormatter = function(maxDecimals) {\n  return function(scalar, units) {\n    var pow = Math.pow(10, maxDecimals);\n    var rounded = Math.round(scalar * pow) / pow;\n\n    return rounded + ' ' + units;\n  };\n};\n\nvar qty = Qty('1.1234 m');\n\n// same units, custom formatter =\u003e '1.12 m'\nqty.format(configurableRoundingFormatter(2));\n\n// convert to 'cm', custom formatter =\u003e '123.4 cm'\nqty.format('cm', configurableRoundingFormatter(1));\n```\n\nCustom formatter can be configured globally by setting `Qty.formatter`.\n\n```javascript\nQty.formatter = configurableRoundingFormatter(2);\nvar qty = Qty('1.1234 m');\nqty.format(); // same units, current default formatter =\u003e '1.12 m'\n```\n\n### Temperatures\n\nLike ruby-units, JS-quantities makes a distinction between a temperature (which\ntechnically is a property) and degrees of temperature (which temperatures are\nmeasured in).\n\nTemperature units (i.e., 'tempK') can be converted back and forth, and will take\ninto account the differences in the zero points of the various scales.\nDifferential temperature (e.g., '100 degC') units behave like most other units.\n\n```javascript\nQty('37 tempC').to('tempF') // =\u003e 98.6 tempF\n```\n\nJS-quantities will throw an error if you attempt to create a temperature unit\nthat would fall below absolute zero.\n\nUnit math on temperatures is fairly limited.\n\n```javascript\nQty('100 tempC').add('10 degC')  // 110 tempC\nQty('100 tempC').sub('10 degC')  // 90 tempC\nQty('100 tempC').add('50 tempC') // throws error\nQty('100 tempC').sub('50 tempC') // 50 degC\nQty('50 tempC').sub('100 tempC') // -50 degC\nQty('100 tempC').mul(scalar)     // 100*scalar tempC\nQty('100 tempC').div(scalar)     // 100/scalar tempC\nQty('100 tempC').mul(qty)        // throws error\nQty('100 tempC').div(qty)        // throws error\nQty('100 tempC*unit')            // throws error\nQty('100 tempC/unit')            // throws error\nQty('100 unit/tempC')            // throws error\nQty('100 tempC').inverse()       // throws error\n```\n\n```javascript\nQty('100 tempC').to('degC') // =\u003e 100 degC\n```\n\nThis conversion references the 0 point on the scale of the temperature unit\n\n```javascript\nQty('100 degC').to('tempC') // =\u003e -173.15 tempC\n```\n\nThese conversions are always interpreted as being relative to absolute zero.\nConversions are probably better done like this...\n\n```javascript\nQty('0 tempC').add('100 degC') // =\u003e 100 tempC\n```\n\n### Errors\n\nEvery error thrown by JS-quantities is an instance of `Qty.Error`.\n\n```javascript\ntry {\n  // code triggering an error inside JS-quantities\n}\ncatch(e) {\n  if(e instanceof Qty.Error) {\n    // ...\n  }\n  else {\n    // ...\n  }\n}\n```\n\n## Tests\n\nTests are implemented with Jasmine (https://github.com/pivotal/jasmine).\nYou could use both HTML and jasmine-node runners.\n\nTo execute specs through HTML runner, just open `SpecRunner.html` file in a\nbrowser to execute them.\n\nTo execute specs through `jasmine-node`, launch:\n\n    make test\n\n### Performance regression test\n\nThere is a small benchmarking HTML page to spot performance regression between\ncurrently checked-out quantities.js and any committed version.\nJust execute:\n\n    make bench\n\nthen open http://0.0.0.0:3000/bench\n\nChecked-out version is benchmarked against HEAD by default but it could be changed by passing\nany commit SHA on the command line. Port (default 3000) is also configurable.\n\n    make bench COMMIT=e0c7fc468 PORT=5000\n\n## TypeScript type declarations\n\nA TypeScript declaration file is published on\n[DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/js-quantities).\n\nIt could be installed with `npm install @types/js-quantities`.\n\n## Contribute\n\nFeedback and contributions are welcomed.\n\nPull requests must pass tests and linting. Please make sure that `make test`\nand `make lint` return no errors before submitting.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgentooboontoo%2Fjs-quantities","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgentooboontoo%2Fjs-quantities","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgentooboontoo%2Fjs-quantities/lists"}