How to use Fractions Library (fraction.js) In Javascript
In this approach using the fraction.js library, we first create fraction objects for the given numerators and denominators. Then, we add these fractions using the add method provided by the library. Finally, we convert the result fraction to its simplest form using toFraction and display it in the console along with the input fractions.
Install the fraction.js library using the below command:
npm i fraction.js
Steps:
- Utilize the
Fraction
constructor provided by thefraction.js
library to create fraction objects for the given numerators and denominators. - Use the
add
method provided by theFraction
objects to add the fractions together. This method handles the addition internally and returns a newFraction
object representing the sum. - To ensure the result is in its simplest form, call the
toFraction
method on the sum fraction object. This method converts the fraction to its simplest form. - Output the result along with the input fractions to the console, showcasing the addition of fractions.
Example: The below example uses Fractions Library to perform the Addition of two fractions using JavaScript.
const Fraction = require('fraction.js');
let num1 = 1;
let den1 = 500;
let num2 = 2;
let den2 = 1500;
let frac1 = new Fraction(num1, den1);
let frac2 = new Fraction(num2, den2);
let tempRes = frac1.add(frac2);
let res = tempRes.toFraction();
console.log(`${num1}/${den1} + ${num2}/${den2} is equal to ${res}`);
Output
1/500 + 2/1500 is equal to 1/300
Time Complexity: O(1)
Auxiliary Space: O(1)
Addition of Two Fractions using JavaScript
Fraction numbers in math are representations of parts of a whole, consisting of a numerator (the part being considered) and a denominator (the total number of equal parts). Add two fractions a/b and c/d and print the answer in simplest form.
Examples:
Input: 1/2 + 3/2
Output: 2/1
Input: 1/3 + 3/9
Output: 2/3
Table of Content
- Using Math Operations
- Using Fractions Library (fraction.js)
Contact Us