In this post, I’ll survey a convenient JavaScript library, math.js, for converting a numeric value having a unit to a value for another unit. I’ll show how to convert a number associated with a unit to a value having another unit, add custom units and conversions, and evaluate textual expressions containing values with units. To wrap up, we’ll walk through a few practical use cases.
By the end of this post, I hope you are inspired to use math.js in your projects. It’s a powerful tool in the right scenarios. With that, let’s get started.
Getting Started
Refer to the docs. You can use math.js in any of several kinds of applications including (but not limited to) Node.js, browser, and CLI. Below, we’ll walk through how to get started in several different environments.
In a JavaScript Module
First, insert the math.js dependency in the package.json
file in your SPA or node application. Carry out one of these alternatives:
npm install mathjs
yarn add math.s
- Insert “math.js” into
package.json
Then, rebuild the node_modules
(e.g., yarn install
or npm install
).
As a Manual Dependency
Alternatively, you could download the math.js library from here to include it in a webpage via a script tag.
CLI – Command Line Interface
Yet another alternative, this is the easier approach if you just want to try math.js units. If you’re using Windows, follow along in the git bash console.
Install math.js globally to expose it as a command-line application. Refer to the docs for more information.
npm install -g mathjs
Units
Among a plethora of capabilities, math.js supports values associated to units. It can use unit values in expressions and calculations. A string expression of the form “value1 unit1 to unit2” returns a new “value2 unit2” string.
The math.unit
method creates a unit. Pass it a value parameter and a unit parameter or else pass a single string value having a unit suffix. It returns a Unit
for a known unit. Here’s an example showing both argument alternatives in a Node app.
const a = math.unit(45, 'cm') const b = math.unit('0.1m') print(a) // 45 cm print(b) // 0.1 m
Basic Unit Conversion
A Unit
has several methods. Use unit.to(unitName)
to carry out a unit conversion, or express it all as a string as mentioned earlier.
Let’s use the math.js CLI to create a new unit value from string notation to illustrate a unit conversion.
- Invoke math.js on a command line (it responds with a prompt).
- Enter a “to-expression” string like “1 yd to ft” (it responds with a result).
Here’s an example interactive math.js CLI unit conversion session converting a pound weight to kilograms as well as converting a kilogram to pounds.
mathjs >1 lb to kg 0.45359237 kg >1 kg to lb 2.2046226218487757 lb >1 yd to ft 3 ft
To use in a Node.js application, the JavaScript code could be:
const aPound = math.unit('1 lb') const aKg = math.unit('1 kg') print(aPound.to('kg')) print(aKg.to('lb'))
Result printed to the console:
0.45359237 kg 2.2046226218488 lb
If it were a browser application, replace those print statements with form setters or emit HTML according to the UI library used.
Calculations
The math.js library contains a unit parser and an expression parser that cooperate in evaluating interpretive math expressions that contain units. The main caveat is to read about temperature conversions on page to units ref if you’re using them.
Here’s an example of a calculation lifted from to units ref.
const a = math.unit(45, 'cm') // Unit 450 mm const b = math.unit('0.1m') // Unit 100 mm math.add(a, b) // Unit 0.55 m math.multiply(b, 2) // Unit 200 mm const c = math.unit(45, 'deg') // Unit 45 deg math.cos(c) // Number 0.7071067811865476
Add Your Own Units with Conversions
See the math.js standard unit strings and built-in constants at units ref. If you need additional user-defined units, you may add them. Refer to units ref as well.
Let’s try in the CLI. We’ll postulate a unit named “gridiron” as having a value of 100 yards. Then we’ll convert a mile to gridiron units and back.
> createUnit('gridiron', '100 yards') gridiron > evaluate('1 mi to gridiron') 17.6 gridiron > evaluate('17.6 gridiron to mi') 1 mi
That worked because maths knows a conversion between miles and yards, and our new unit is defined in yards.
If we cannot express a new unit in terms of an existing unit, then we can create a new base unit.
> createUnit('longway') longway > evaluate('4 longway * 1000 mi') 4000 longway mi >
Mass-Create Several Units
In an application, we can pass added units in a JavaScript object to the createUnit
method. Here’s the example lifted from page units ref:
Mathjs.createUnit( { foo: { prefixes: 'long', baseName: 'essence-of-foo' }, bar: '40 foo', baz: { definition: '1 bar/hour', prefixes: 'long' } }, { override: true }) Mathjs.evaluate('50000 kilofoo/s') // 4.5 gigabaz
Miscellaneous
See the units ref page for more bells and whistles:
- Decimal unit prefixes such as ‘G’ and ‘giga’ or ‘milli’ and ‘m’
- Binary prefixes for use with bits and bytes units
- Universal constants
- Physical constants
- Electromagnetic contents
- Nuclear and atomic constants
- Physio-chemical constants
- Adopted values
Use Cases
Several brainstormed use cases come to mind.
UnitValue React Component
Consider a formula evaluation application that accepts user input in a form where some numeric fields each have a value assumed to have a unit. The fields feed a back-end application that evaluates inputs as formula terms and factors. Maybe it’s a distance formula using metric units.
The input form could have UnitValue components that wrap a standard HTML input type of number along with a dropdown of options containing units. Let’s say the component contains a number 1 and the dropdown selected element is “mile.” If the user selects “feet” from the dropdown, a handler within the UnitValue component calls math.js to convert “1 mile to feet,” storing the result int value, 5,280 in the number input.
A backend request handler could call math.js to normalize the unit to whatever it preferred, or the client could normalize the unit, to say “km.”
Calculator App That includes Units
Remember that math.js can interpret strings as multi-term calculations that include values with units. We could create a UI that validates against harmful inputs as it creates an evaluation string fed to math.js. A tokenizer and parser could accommodate validation as it forms the input to math.js. The result would render in a result field resembling that of a physical calculator.
Unit Conversion Calculator
A local app would be an alternative to using web-based unit conversions. Some fields don’t have units or conversions online. Nuclear radiation has several exposure dose unit conversions that are available as copy/paste values to feed to a calculator. We could use math.js to make a custom exposure dose calculator.
Ad Hoc Conversions on Request-Response Data
Sometimes a backend database or process returns value units that we want to convert other units suitable for a certain interactive audience. For example, a backend may return metric units, but some denizens of some countries are more comfortable with imperial units. A client application could have a local state that drives a conversion decision carried out by math.js.
Conclusion
In this post we covered using math.js to convert a number associated with a unit to a value having another unit, add custom units and conversions, and evaluate textual expressions containing values with units. Additionally, we mentioned bundled unit prefix support, such as “giga”, that there are well-known contents contained in mathjs, and suggested use cases
Overall, mathjs-provided unit conversions are convenient and powerful, and it additionally has an abundance of other math manipulations that may be worth adding to your arsenal. I’d recommend taking a look at what it has to offer and how it can benefit your process as soon as you can.
Have a thought to add? Leave me a comment below. Check out the Keyhole Dev Blog for more content!