Decimal to Fraction in JavaScript

javascript

Solution

You can't "split" numbers.

If you look at the console, you'll see

Uncaught TypeError: Object 1.75 has no method 'split'

You should be using the JavaScript section on JSBin, it'll show you errors like this in a red box at the bottom.

Easiest fix? Make it a string by either writing it as a string literal:

var decimal = '1.75';

Or call `.toString()` before splitting:

var decimalArray = decimal.toString().split(".");

And numerator is on top:

document.write(numerator + " / " + denominator);

Problem

I wrote this simple script to convert a decimal to a fraction but it is not working. Nothing is outputted. ``` var decimal = 1.75; var decimalArray = decimal.split("."); // 1.75 var leftDecimalPart = decimalArray[0]; // 1 var rightDecimalPart = decimalArray[1]; // 75 var numerator = leftDecimalPart + rightDecimalPart; // 175 var denominator = Math.pow(10, rightDecimalPart.length); // 100 document.write(numerator + " / " + denominator); ``` JS Bin: http://jsbin.com/exepir/1/edit

Original source

Related problems