Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal to Fraction in JavaScript

Tags:

javascript

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

like image 589
user1822824 Avatar asked Dec 15 '22 14:12

user1822824


1 Answers

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);
like image 151
sachleen Avatar answered Dec 28 '22 23:12

sachleen