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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With