Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Converting a proper fraction to mixed fraction - JavaScript
A proper fraction is one where the numerator is smaller than the denominator, represented in p/q form where both p and q are natural numbers.
What is a Mixed Fraction?
When we divide the numerator (a) of a fraction by its denominator (b), we get a quotient (q) and remainder (r). The mixed fraction form for fraction a/b is:
This is pronounced as "q wholes and r by b".
Problem Statement
We need to write a JavaScript function that takes an array of two numbers representing a proper fraction and returns an array with three numbers representing its mixed form.
Algorithm
To convert proper fraction to mixed fraction:
- Calculate quotient using Math.floor(numerator / denominator)
- Calculate remainder using numerator % denominator
- If remainder is 0, return only the quotient
- Otherwise, return [quotient, remainder, denominator]
Example
const arr = [43, 13];
const properToMixed = arr => {
const quotient = Math.floor(arr[0] / arr[1]);
const remainder = arr[0] % arr[1];
if(remainder === 0) {
return [quotient];
} else {
return [quotient, remainder, arr[1]];
}
};
console.log(properToMixed(arr));
console.log("43/13 = 3 wholes and 4/13");
[ 3, 4, 13 ] 43/13 = 3 wholes and 4/13
Additional Examples
// Test with different fractions console.log(properToMixed([17, 5])); // 17/5 = 3 2/5 console.log(properToMixed([25, 4])); // 25/4 = 6 1/4 console.log(properToMixed([20, 5])); // 20/5 = 4 (whole number)
[ 3, 2, 5 ] [ 6, 1, 4 ] [ 4 ]
Conclusion
Converting proper fractions to mixed fractions involves simple division to find quotient and remainder. This function handles both cases where the division results in a whole number or leaves a remainder.
