Skip to content

Math.js: Fractions

While JS Calc (and Math.js) performs most calculations using floating-point numbers by default, it also supports precise arithmetic with fractions. This is useful when you need to avoid potential floating-point inaccuracies for rational number calculations.

Creating Fractions

To work with fractions precisely, you must explicitly create them using the fraction() function.

Syntax:

  • fraction(numerator, denominator)
  • fraction(decimalValue)
  • fraction(stringRepresentation)

Examples:

> fraction(1, 3)
 1/3

> fraction(0.5)
 1/2

> fraction("2/7")
 2/7

> fraction("0.125")
 1/8

If you simply type 1/3 without the fraction() function, it will be evaluated as a floating-point number:

> 1/3
 0.3333333333333333

Arithmetic with Fractions

Once numbers are defined as fractions, arithmetic operations between them (or between fractions and integers) will maintain precision and return fractional results where possible.

> f1 = fraction(1, 2)
> f2 = fraction(1, 3)
> f1 + f2
 5/6

> f1 - f2
 1/6

> f1 * f2
 1/6

> f1 / f2
 3/2

> fraction(3, 4)^2
 9/16

> 2 * fraction(1, 7)
 2/7

If an operation involves a fraction and a floating-point number that cannot be perfectly represented as a fraction, the result will typically be a floating-point number:

Example: 0.1 cannot be perfectly represented as a simple fraction by default

> fraction(1,3) + 0.1
 0.4333333333333333

Output

Fractional results are displayed in the n/d format. If the denominator is 1, it's displayed as an integer.

When to Use Fractions

  • When exact rational arithmetic is crucial and floating-point approximations are not acceptable.
  • For problems in number theory or combinatorics where exact fractional results are needed.

For most everyday calculations, standard floating-point arithmetic is usually sufficient and faster.

Refer to the Math.js Fractions Documentation for more details.