JavaScript class for processing fractions

View the Project on GitHub craigsapp/RationalNumber

RationalNumber is an implementation of rational numbers in JavaScript that manages fractions consisting of two integers. Mathematical operations such as addition, subtraction, multiplication and division are provided. Division by zero is allowed and should produce correct mathematical results according to the use of Infinity and NaN in JavaScript.

Fractions are maintained by default in reduced form. For example, setting the value to 2/4 will automatically be reduced (simplified) to 1/2. However functions for forcing non-reduced fractions are provided, particularly for avoiding speed issues in intermediate calculations (although the current mathematical functions will reduce the fraction after every calculation to minimize the chance of overflow).

This implementation limits the numerator and denominator to the range from 0 to 253–1 plus a sign, and optional automatic overflow detection is included by running checkOverflowOn(), and CheckOverflowOff() turning this feature off.

RationalNumber demonstration

The following section uses the RationalNumber Javascript code to dynamically process rational numbers. Try typing various values in the four boxes below to create rational numbers. The reduced forms of the number will be shown to the right, and example mathematical calculations using the two rational numbers is given further below. Try typing a very large number to see what happens when any number has an absolute value greater or equal to 253.

numerator 1:
denominator 1:
rational number:
mixed fraction:

numerator 2:
denominator 2:
rational number:
mixed fraction:
The two numbers you enter above are used in the following calculations. Each calculation is shown in plain, mixed and floating-point versions.

Using in node applications

This code can be installed globally for use in node with the command:

$ npm install -g rational-number

If you want to install locally within anode project, then install as a package dependency with the command:

$ npm install --save rational-number

Here is an code example which loads the module into a node script, creates two RationalNumbers (4/5 and 13/2), adds them, and then prints the result to the console:

var RationalNumber = require('rational-number');

var rn1 = new RationalNumber(4, 5);
var rn2 = new RationalNumber('26/4');
var rn3 = rn1.add(rn2);
console.log(rn1.valueOf()+" + "+rn2.valueOf()+" = "+rn3.valueOf());

The above code should output the following text to the console:

4/5 + 13/2 = 73/10
4/5 + 6_1/2 = 7_3/10
0.8 + 6.5 = 7.3

Using in a web browser

The JavaScript code for rational numbers can also be used stand-alone within a webpage by including these two files:

<script src="RationalNumber-base.js"></script>
<script src="RationalNumber-math.js"></script>

The first file (RationalNumber-base.js) is required, while the second one containing mathematical functions (add, subtract, etc.) is optional. The RationalNumber repository's lib directory contains a makefile with example commands to generate minified versions of the JavaScript programs.


Input and output from the RationalNumber code can be tested using mocha and the JavaScript files in the test directory of the repository. To test from a node installation:

$ npm install   # to download mocha dependency if necessary
$ npm test

If you have mocha installed globally in your search path (such as with "npm install -g mocha"), you can also type one of the following equivalent shell commands to run the code tests:

$ make test
$ mocha test
$ cd test; make
$ cd test; mocha

RationalNumber methods

Click on the entries below to view documentation and examples for each RationalNumber method. Code examples can be run in the JavaScript console for this page since it has already loaded a copy of the RationalNumber code. Press ctrl + +/= to open all documentation, ctrl+ to close all documentation, and ctrl+e to toggle display of all code examples. shft+click will open documentation for a single method and close all other entries.

getNumerator — Return the numerator, including sign.
getNumeratorAbsoluteValue — Return the numerator, excluding sign.
setNumerator — Set the numerator, reducing fraction if necessary.
setNumeratorNoReduce — Set the numerator but don't reduce fraction.
setNumeratorAbsoluteValueNoReduce — Sets numerator without changing sign or reducing.
getDenominator — Return the denominator (always non-negative).
setDenominatorAbsoluteValue — Set the denominator (sign ignored).
setDenominatorAbsoluteValueNoReduce — Set denominator, not trying to reduce the fraction.
setValue — Set the numerator and denominator (sign can be on either or both).
setValueNoReduce — Set the numerator and denominator, but don't try to reduce.
getSign — Returns –1 if negative, +1 otherwise.
setSign — Set the sign to positive or negative.
reduce — Reduce the fraction if needed.
valueOf — Return a floating-point copy of the rational number.
   toFloat — Alias for valueOf method.
   toNumber — Alias for valueOf method.
toString — Convert to a string in the form "n/d".
toStringMixed — Return a string as a mixed fraction.
toJSON — Create a JSON string.
toFloatJSON — Create a float/fractional remainder JSON string.
toFloatArray — Create a float/fractional remainder Array.
fromString — Read number from string.
fromStringNoReduce — Read number from string without reducing.
parseString — Return a new RationalNumber rather than changing current object.
clone — Make a new copy of the RationalNumber.
copy — Copy the value of another RationalNumber.
checkOverflow — Same as isSafe(), but throws an error.
checkOverflowOn — Force validity check for overflows.
checkOverflowOff — Turn off automatic overflow validity checks.
isSafe — Numerator and denominator both less than 253.
isNaN — Returns true if equal to 0/0.
isInfinite — Returns true if denominator is 0 and numerator is not.
isValid — Returns true if safe, finite and not NaN.
isEqual — Return true if sign, numerator and denominator of two numbers are identical.
isPositive — Returns true if larger than 0.
isNegative — Returns true if smaller than 0.
isInteger — Returns true if denominator is 1.


Mathematical functions

The following RationalNumber methods provide additional arithmetic processing from the optional RationalNumber-math.js file:

abs — Return non-negative copy of the rational number.
invert — Switch the numerator and denominator.
getInversion — Return a reciprocal copy of called object.
   inversion — Alias for getInversion method.
negate — Make positive values negative and vice-versa.
getNegation — Return a copy of the object, with sign reversed.
   negation — Alias for getNegation method.
addTo — To this RationalNumber, add additional numbers.
add — Similar to addTo(), but returns sum rather than altering contents.
subtractTo — To this RationalNumber, subtract values.
subtract — Similar to subtractTo(), but returns result rather than altering calling object.
multiplyTo — To this RationalNumber, multiply values.
multiply — Similar to multiplyTo(), but returns result rather than altering calling object.
divideTo — To this RationalNumber, divide values.
divide — Similar to divideTo(), but returns result rather than altering calling object.