fraction.js

repository·main·Indexed 20 days ago

https://github.com/rawify/fraction.js

A high-precision rational number library for JavaScript using BigInt to represent numerators and denominators. It avoids floating-point inaccuracies and supports exact fractions, repeating decimals in strings, and various input formats including arrays, objects, and LaTeX output. Version 5.3.4.

Tokens
4.5K
Snippets
17
Records
23
Agent score
69%

What's inside fraction.js

  1. Handle repeating decimals in strings

    main

    Fraction.js supports repeating decimals using parentheses or single quotes to denote the repeating part. This allows for exact rational representation of numbers that would otherwise be imprecise in floating-point.

    Supported syntax examples:

    • "0.(3)" or "0.'3'" for $0.333...$
    • "123.45(6)" for $123.45666...$
    • "123.45'6'" for $123.45666...$
    • "123.(456)" for $123.456456...$
    var f = new Fraction("123.32");
    // Dividing by a repeating decimal string
    console.log(f.div("33.6(567)"));
  2. Import and Initialize Fraction.js

    main

    Depending on your environment, use one of the following methods to include Fraction.js in your project.

    Node.js (CommonJS)

    const Fraction = require('fraction.js');

    ESM (ECMAScript Modules)

    import Fraction from 'fraction.js';

    Browser (Script Tag)

    Include the minified file in your HTML:

    <script src="path/to/fraction.min.js"></script>
    <script>
      var x = new Fraction("13/4");
    </script>
  3. Perform mathematical modulo operations

    main

    The standard .mod() method in Fraction.js behaves like typical computer science modulo (often resulting in different behavior for negative numbers than pure mathematics).

    To achieve the mathematically correct modulo (where the result is always within the range of the divisor), use the following pattern:

    new Fraction(a).mod(b).add(b).mod(b)

    var a = -1;
    var b = 10.99;
    
    // Standard modulo (not mathematically correct for negative congruences)
    console.log(new Fraction(a).mod(b)); 
    
    // Mathematically correct modulo
    console.log(new Fraction(a).mod(b).add(b).mod(b));
  4. Understand FractionInput types

    main

    The FractionInput type defines what can be passed into most Fraction methods (like add, sub, equals, etc.). It supports:

    • Fraction instance
    • number
    • bigint
    • string (e.g., "1/2")
    • [number | bigint | string, number | bigint | string] (a tuple of [numerator, denominator])
    • NumeratorDenominator object: { n: number | bigint; d: number | bigint; }
  5. Handle Fraction.js Exceptions

    main

    Fraction.js throws exceptions for critical errors such as:

    • Parsing errors (invalid input strings)
    • Division by zero

    Ensure you wrap your logic in try...catch blocks when dealing with untrusted input or mathematical operations that might result in division by zero.

  6. Rounding and Integer Conversion

    main

    Methods for converting fractions to integers or rounding them.

    MethodDescription
    ceil([places=0-16])Returns the ceiling of the rational number using Math.ceil
    floor([places=0-16])Returns the floor of the rational number using Math.floor
    round([places=0-16])Returns the rational number rounded using Math.round
    roundTo(multiple)Rounds the fraction to the closest multiple of another fraction
  7. Initialize a Fraction

    main

    You can create a new Fraction instance using several input formats. The constructor and all math functions parse these inputs and automatically reduce them to the smallest possible term. Supported formats include:

    • Two arguments: new Fraction(numerator, denominator)
    • Arrays: new Fraction([numerator, denominator])
    • Objects: new Fraction({n: numerator, d: denominator})
    • Integers: new Fraction(123)
    • Doubles: new Fraction(55.4) (Note: For very large numbers, use strings to avoid floating-point precision issues during initialization)
    • Strings: Supports various rational representations including "123/45", "123:45", "4 123/45", and repeating decimals like "123.(456)" or "123.45(6)".
    new Fraction(3, 2);           // 3/2 = 1.5
    new Fraction([1, 2]);        // 1/2
    new Fraction({n: 1, d: 2}); // 1/2
    new Fraction("123/45");    // Rational string
    new Fraction("123.(456)"); // Repeating decimal string
  8. Convert Decimals to Fractions with Error Tolerance

    main

    Fraction.js can convert decimal numbers into precise fraction strings. You can use .toFraction(true) for a mixed number string format (e.g., "1 22/25").

    If you are working with imprecise decimals and want to find the closest rational representation within a certain error margin, use .simplify(error) before converting.

    // Mixed number string
    let x = new Fraction(1.88);
    let res = x.toFraction(true); // "1 22/25"
    
    // Simplify with error tolerance
    let y = new Fraction(0.33333);
    let simplified = y.simplify(0.001).toFraction(); // "1/3"
  9. Comparison and Logical Operations

    main

    Use these methods to compare two rational numbers or check divisibility.

    Equality and Comparison

    • equals(n): Returns true if two rational numbers are equal.
    • lt(n): Returns true if the fraction is less than n.
    • lte(n): Returns true if the fraction is less than or equal to n.
    • gt(n): Returns true if the fraction is greater than n.
    • gte(n): Returns true if the fraction is greater than or equal to n.
    • compare(n): Returns an integer:
      • < 0: n is greater than the actual number
      • > 0: n is smaller than the actual number
      • = 0: n is equal to the actual number

    Divisibility

    • divisible(n): Returns true if n divides the current fraction.
  10. Convert Fraction to String, LaTeX, or Decimal

    main

    Methods for converting a Fraction object into different formats.

    Decimal Representation

    • valueOf(): Returns a decimal representation of the fraction.
    • toString([decimalPlaces=15]): Generates an exact string representation. For repeating decimals, digits within repeating cycles are enclosed in parentheses, e.g., 1/3 becomes "0.(3)".

    Note on implicit conversion: When using the + operator with a string (e.g., "123" + new Fraction), valueOf() is called first. To ensure toString() behavior, call it explicitly.

    LaTeX and Fraction Strings

    • toLatex(showMixed=false): Generates an exact LaTeX representation. If showMixed is true, it returns mixed fractions (e.g., "1 1/3" instead of "4/3").
    • toFraction(showMixed=false): Returns a string representation of the fraction. If showMixed is true, it returns mixed fractions (e.g., "1 1/3" instead of "4/3").

    Continued Fractions

    • toContinued(): Returns an array representing the fraction as a continued fraction. The first element is the whole part.
    var f = new Fraction('88/33');
    var c = f.toContinued(); // [2, 1, 2]
    var f = new Fraction('88/33');
    var c = f.toContinued(); // [2, 1, 2]
  11. Arithmetic Operations with Fraction

    main

    The Fraction class provides several methods for performing arithmetic on rational numbers. Most methods return a new Fraction object.

    MethodDescription
    abs()Returns the absolute value (removes sign)
    neg()Returns the additive inverse (flips sign)
    add(n)Returns the sum of the fraction and n
    sub(n)Returns the difference of the fraction and n
    mul(n)Returns the product of the fraction and n
    div(n)Returns the quotient of the fraction and n
    pow(exp)Returns the power of the fraction raised to a rational exponent. Returns null if the result is non-rational
    log(base)Returns the logarithm to a rational base. Returns null if the result is non-rational
    mod(n)Returns the modulus (remainder) of the division (similar to % operator)
    mod()Returns the modulus of the numerator and denominator
    gcd(n)Returns the fractional greatest common divisor
    lcm(n)Returns the fractional least common multiple
    inverse()Returns the multiplicative inverse (reciprocal)
    simplify([eps=0.001])Simplifies the rational number under a specific error threshold
    clone()Creates a copy of the current Fraction object