Units and quantities
@ratmath/core/units attaches units to exact numbers. Every conversion factor is an exact rational (times a power of for angles), so a mile is exactly 1609.344 metres and nothing is rounded until you ask for digits.
import { Q, units, constants } from "@ratmath/core/units";
Q("9.8 m/s^2").multiply(Q(3, "kg")).to("N"); // 147/5 N
Q(1, "mi").to("km"); // 25146/15625 km
Q("20 degC").to("degF"); // 68 degF
Q(2, "m").divide(Q(4, "cm")); // 50, a plain number
Quantities
Q(value, unit) or Q("value unit") makes a Quantity. The value is anything Core reads exactly: a Core number, a bigint, a safe integer, or a literal string such as "9.8", "1/3", "0.#3" or "1.2[3:6]". A JavaScript float like 9.8 is refused, as in R, because it is not the number you typed.
The quantity keeps its value in the unit it was written in. to(unit) converts, valueIn(unit) gives just the number, toBase() writes it in coherent SI base units and simplify() picks a named coherent unit when there is one (3/2 J/s becomes 3/2 W).
add and subtract need the same dimensions and answer in the left unit. multiply, divide, inverse and pow combine units; when the dimensions cancel the result is a plain number.
Unit expressions
units.parse reads products, quotients and integer powers: "kg*m^2/s^2", "N m" (a space multiplies), "m/(s*kg)", "m·s⁻²", "1/s". Division is left to right, so "m/s*kg" is ; units print with parentheses whenever a denominator has more than one factor, so printed units always parse back. toString({ style: "unicode" }) prints kg·m²/s².
SI prefixes work on the units that take them (km, mL, µs or us, kWh, mAh, MeV, also spelled out as kilometre), and binary prefixes on bits and bytes (KiB, MiB). An exact name always wins, so min is a minute and pt a pint.
Dimensions
The base dimensions are Mass, Length, Time, Current, Temperature, Amount, Luminosity, Angle, Information and Money, with coherent units kg, m, s, A, K, mol, cd, rad, bit and USD. Angle counts as a dimension so that degrees cannot be added to metres; Information so that bytes cannot be added to seconds. Adding, subtracting, comparing or converting across dimensions throws and names both dimensions.
Angles and
A unit's size is base units with rational and an integer. A degree is rad, a turn rad, a parsec au. Conversions between units with the same power of stay rational: 90 degrees is exactly a quarter turn. Converting radians to degrees needs itself, and then the answer is an exact interval that contains the true value, good to about 33 digits.
Temperatures
Celsius and Fahrenheit readings are points on a scale with a shifted zero, so they follow different rules from other quantities:
degCanddegFare points. Converting between them, or toK, applies the offset:Q("20 degC").to("degF")is 68 degF.- Point minus point is a difference:
Q("20 degC").subtract(Q("50 degF"))is10 deltaDegC. Point plus difference is a point. Point plus point throws. deltaK,deltaDegCanddeltaDegFare differences and cannot be read as points.Kis absolute, so it works either way:Q("300 K").to("degC")is 26.85 °C.- Multiplying, dividing or raising a
degCordegFvalue throws; convert toKfirst.
Money
US money is exact: USD (also dollar), cent, and the coins penny, nickel, dime and quarter, each with its plural. Three quarters, two dimes and four pennies are exactly 99 cents: Q("3 quarter").add(Q("2 dime")).add(Q("4 penny")).to("cent"). Money is its own dimension, so dollars cannot be added to metres.
Clock times
toClock() writes a duration as h:mm, and toClock({ seconds: true }) as h:mm:ss: 195 minutes is 3:15. With wrap: 12 or 24 it reads the duration as a time of day after midnight, so 13.5 h is 1:30 on a 12-hour clock. Nothing is rounded silently: a duration that is not a whole number of minutes (or seconds) is refused unless you pass a rounding mode as round. Fractional seconds that end, such as 1.25 s, are written as a decimal.
Q("150 min").add(Q("45 min")).toClock(); // "3:15": 45 minutes after 2:30
Q("3725 s").toClock({ seconds: true }); // "1:02:05"
Q("100 s").toClock({ round: "half-up" }); // "0:02"
Classroom clock times and dates
Warning: this is not a date library. clock and simpleDate are small exact helpers for classroom explorations: elapsed time, AM and PM, leap years, days in a month, days between dates and the day of the week. They know nothing about time zones, daylight saving time, leap seconds, locales or historical calendars (dates before 1582 are proleptic Gregorian, not the Julian dates people used). For real dates and times use Temporal (Temporal.PlainDate, Temporal.PlainTime, Temporal.ZonedDateTime) where your runtime has it, or its polyfill @js-temporal/polyfill, or a maintained library such as Luxon or date-fns (with date-fns-tz for zones). The same warning is exported as the string NOT_A_DATE_LIBRARY.
clock("9:45 AM"), clock("21:05") or clock(9, 45) makes a time of day, to the second. add and subtract take a time Quantity or a string such as "2 h" and wrap around midnight; daysLater on the result counts the midnights crossed. until(later) is the elapsed time going forward, past midnight if needed, as a Quantity, so toClock() writes it as hours and minutes. Durations must be whole seconds.
clock("9:45 AM").add("150 min").toString(); // "12:15 PM"
clock("10:30 PM").until(clock("1:15 AM")).toClock(); // "2:45"
clock("10:30 PM").add("3 h").daysLater; // 1 (it is 1:30 AM the next day)
clock("13:05").toString({ hours: 24 }); // "13:05"
simpleDate("2026-11-28") or simpleDate(2026, 11, 28) makes a date from year 1 to 9999. It has weekdayName, monthName, dayOfYear, isLeapYear and daysInMonth, and addDays(n) and daysUntil(other) count whole days. isLeapYear(year) and daysInMonth(year, month) are also plain functions.
simpleDate("1776-07-04").weekdayName; // "Thursday"
simpleDate("2026-11-28").daysUntil("2027-01-01"); // 34
isLeapYear(1900); // false: centuries need 400
simpleDate(2024, 2, 28).addDays(1).toString(); // "2024-02-29"
Intervals
An interval magnitude converts by the same exact factor, so it gets no wider: Q("1.2[3:6] m").to("cm") is 123:126 cm. relation(other) returns the Relation mask of possible orderings, compare returns −1, 0 or 1 and throws when overlapping intervals leave the order undecided, and equals is true only when the two are certainly equal.
Constants
constants holds the exact SI defining constants c, h, e, kB and NA, the gas constant R (their product kB·NA, so also exact), standard gravity g0, and the measured G as an interval of its CODATA 2018 value plus or minus one standard uncertainty.
Your own units
units.extend() copies the standard catalogue so you can add to it without changing it for anyone else. define(name, definition, options) takes a string such as "201.168 m", a Quantity, a Unit or a raw { dimensions, scale, piPower }, with optional aliases, prefixes: "SI" and a group. groups() lists named units by group, for a unit menu. register(key, unit) makes an existing Unit reachable under another key while keeping the same object, so a host can build a catalogue from units it already holds; prefixes follow the unit's own prefixes field.
extend({ scalars }) swaps the arithmetic on magnitudes. The RiX language uses this to pass its exact symbolic and algebraic numbers, so in RiX a radian-to-degree conversion stays exact.
const mine = units.extend();
mine.define("furlong", "201.168 m", { aliases: ["furlongs"] });
mine.define("fortnight", "14 day");
mine.quantity("1 furlong/fortnight").to("mm/h"); // 4191/7 mm/h, exactly
@ratmath/core in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.