Bite-Size Tips: Decimal to Simple Fraction JS

Challenge:

Given a number convert it to a simple fraction. Where the result is a string that looks like this: “1/2”, “7/2”, etc.

Approach:

  1. Find the correcponding base taking counting how many digits there after the dot.
  2. Multiply the numberator by that base.
  3. Find the greatest common denominator for the number and the base.
  4. Return string representation of the fraction.
  5. Account for edge cases of being presented with a zero or an integer.

Solution:

var toFraction = function(num) {
if (num === 0) {return '0/1'}
let str = num.toString();
let arr = str.split('.');
let base = '1';
if (arr[1] === undefined){return `${num}/1`}
for (let i = 0; i <= arr[1].length; i++){
base = base + '0';
}
base = Number(base);
num = num * base;
for (let i = base; i >= 0; i-- ){
if (num%i === 0 && base % i === 0){
return `${num/i}/${base/i}`
}
}
return `${num}/${base}`
};