Open In App

How to Work with Fractions in Math.js?

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Math.js is a JavaScript library that can handle various mathematical operations, including fractions. It makes it easy to perform calculations with fractions, convert them to decimals, and simplify them. This guide will show you how to work with fractions using math.js.

To work with fractions, we need to install math.js library. Use the below command to install it:

npm install mathjs

These are the following topics that we are going to discuss:

Basic Fraction Operations

Addition:

Adding two fractions involves finding a common denominator, summing the numerators, and simplifying the result.

Example: This adds two fractions using mathjs library and prints the result.

JavaScript
const math = require('mathjs');
let result = math.add(math.fraction('2/5'), math.fraction('1/10'));
console.log(math.format(result, { result: 'ratio' }));

Output:

1/2

Multiplication:

To Multiply the fractions we have to multiply numerators together and the denominators together.

Example: This multiplies two fractions using mathjs library and prints the result.

JavaScript
const math = require('mathjs');
let result = math.multiply(math.fraction('2/5'), math.fraction('1/10'));
console.log(math.format(result, { result: 'ratio' }));
1/25

Converting Decimal to Fraction

For conversion of Decimal to Fraction we convert a decimal to a fraction by expressing it as a fraction with a power of 10 as the denominator.

Example: This demonstrates the conversion of the decimal 0.6 to a fraction and prints it in fractional form using the mathjs library.

JavaScript
const math = require('mathjs');
let fraction = math.fraction(0.6);
console.log(math.format(fraction, { fraction: 'ratio' }));

Output:

3/5

Simplifying a Fraction

Fractions can be simplified by dividing the numerator and denominator by their greatest common divisor (GCD).

Example: This illustrates the creation of the fraction 6/9, simplifies it, and prints the result in fractional form using the mathjs library.

JavaScript
const math = require('mathjs');

// Create a fraction and simplify it
let fraction = math.fraction('6/9');
console.log(math.format(fraction, { fraction: 'ratio' }));

Output:

2/3

Next Article

Similar Reads