4

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

VisioN
  • 143,310
  • 32
  • 282
  • 281
user1822824
  • 2,478
  • 6
  • 41
  • 65

3 Answers3

8

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);
sachleen
  • 30,730
  • 8
  • 78
  • 73
2

Since working with strings is not the best way to solve your problem, I'd suggest you a fast alternative solution which works with numbers only:

var decimal = 1.75,
    numerator = decimal,
    denominator = 1;

while (numerator % 1) numerator *= 10;
denominator = numerator / decimal;

console.log(numerator + " / " + denominator);
// >> "175 / 100"
VisioN
  • 143,310
  • 32
  • 282
  • 281
2

If you want to make sure it works in the general case, I would rely on a well tested library, like Fraction.js.

var f = new Fraction(1.75);

console.log(f.toFraction()); // Results "1 3/4"
console.log(f.s * f.n + " / " + f.d); // Results "7 / 4"
console.log(f.toString()); // Results "1.75"