<p>Decimal to fraction converter emulating a casio calculator</p>
<p>The calculator will attempt to estimate the result after a fixed amount of digits.</p>
<p>The calculator will not display the calculated fraction or continue to calculate the fraction if the denominator > max denominator or the limit of trial of is exceeded</p>
<input id="decimal" type="text">
<pre id="output"></pre>
JavaScript
$(function(){
var $i = $("#decimal");
var $o = $("#output");
$i.on("keyup", function(){
var iV = $i.val();
$o.text("");
//start evaluation
if (iV.indexOf(".") > -1) {
var whole = iV.match(/^(\d*)\.\d*$/)[1] || "0";
var decimal = iV.match(/^\d*\.(\d*)$/)[1] || "0";
if (decimal.length > 15) decimal = decimal.substr(0,15);
var numOfDecimals = decimal.length;
var maxTrial = 2000;
var maxDenominator = 10000;
if (iV.length >= 12) {
//try brute force
$o.append("used brute force\n");
var tryDecimal = decimal/Math.pow(10,numOfDecimals);
var actualVal = tryDecimal;
var numerator = 0;
var denominator = 1;
var epsilon = 10e-14;
var delta = 2;
var updateNumbers = function() {
delta = numerator/denominator - tryDecimal;
return Math.abs(delta);
};
while (updateNumbers() > epsilon && --maxTrial && denominator <= maxDenominator) {
if (delta > epsilon)
denominator++;
else
numerator++;
}
if (numerator == 0)
printResult(whole);
else if (numerator == denominator) {
printResult(++whole);
} else if(!maxTrial || denominator > maxDenominator) {
printResult(iV, "max trial reached");
} else
printResult((whole>0?whole+"/":"")+numerator+"/"+denominator);
} else if (decimal > 0) {
//attempt conversion
$o.append("used conversion\n");
var denominator = Math.pow(10, numOfDecimals);
var numerator = decimal;
var divisor = hcf(numerator, denominator);
if (denominator/divisor > maxDenominator)
printResult(iV, "divisor > maxDenominator");
else
printResult((whole>0?whole+"/":"")+numerator/divisor+"/"+denominator/divisor);
} else {
$o.append("simply parsed as integer\n");
printResult(parseInt(iV));
}
} else...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.