JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
</head>
<body>
<h1>Convert a Decimal to a Simplified Fraction</h1>
<p>Check out <a href="http://bateru.com/news/2012/05/code-of-the-day-javascript-convert-decimal-to-a-simplified-fraction/">http://bateru.com/new</a> for more information.<br/>
Created by Larry Battle</p>
<div name="page">
Input: <input type="text" id="input"><br/>
Output: <input type="text" id="output">
</div>
<hr/>
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
</body>
</html>
JavaScript
/**
* @author Larry Battle <http://bateru.com/news/contact-me>
* @license MIT
* @version 1.0
* @date May 08, 2012
* @purpose To provide a function that converts a decimal to a simplified fraction.
* @info <http://bateru.com/news/2012/05/code-of-the-day-javascript-convert-decimal-to-a-simplified-fraction/>
*/
// ###
// Main Code
// ###
var mixin = {};
mixin.getKeys = function (obj) {
var props = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
props.push(prop);
}
}
return props;
};
mixin.getFractionObject = (function () {
var obj = {
0 : '0',
1 : '1'
},
num = 10,
den = 11,
value;
while (--num) {
while (--den > 1) {
value = (num / den).toFixed(3);
if (value < 1) {
obj[value] = num + "/" + den;
}
}
den = 11;
}
obj.keys = mixin.getKeys(obj);
return function () {
return obj;
};
}
());
mixin.getClosestNum = function (arr, val) {
if (typeof arr !== "object" || !(arr.hasOwnProperty('length')) || isNaN(val)) {
return false;
}
var i = arr.length,
j = i - 1,
minDiff = Math.abs(+val - arr[j]),
diff;
while (i--) {
diff = Math.abs(+val - arr[i]);
if (diff < minDiff) {
minDiff = diff;
j = i;
}
}
return arr[j];
};
mixin.getFractionFromDecimal = function (dec) {
if (isNaN(dec) || !isFinite(dec)) {
return false;
}
if (!/\./.test(dec)) {
return dec;
}
var fracs = mixin.getFractionObject(),
matches = dec.toString().match(/(\d+)(\.\d+)/),
fraction = fracs[mixin.getClosestNum(fracs.keys, Math.abs(+matches[2]))],
sign = ( 0 < dec || (fraction == "0" && Math.abs(dec) < 1) ) ? '' : '-';
if (1 < Math.abs(dec)) {
if (isNaN(fraction)) {
fraction = +matches[1] + " " + fraction;
} else {
fraction = +matches[1]...