Forum Moderators: open
function decfrac(DtF)
{
var dec = DtF
var decString = dec.toString();
var dslength = decString.length - 1;
var div = 1;
// Multiply by powers of 10 to remove the decimal
for (i=0; i<dslength; i++)
{
dec = dec * 10;
div = div * 10;
}
// Factor out the GCF of the two numbers
for (i=2; i <= dec; i++) {
while ((mod(dec,i) == 0) && (mod(div,i) == 0))
{
dec = dec/i;
div = div/i;
}
}
expF = dec + "/" + div;
return expF;
}
function mod(n, m)
{
while (n >= m)
{
n = n-m;
}
return(n);
/*Keeps subtracting the number you want to divide by until the remainder is less than the original divisor, and then returning the remainder.
*/
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title></title>
<style type="text/css">
label {
display:block;
margin-bottom:10px;
}
#fraction {
margin-top:10px;
}
</style>
<script type="text/javascript">
function decfrac(DtF) {
dec=DtF;
if((isNaN(dec))||(dec=='0.')){
alert('please insert some numbers in the box !');
df.reset();
return;
}
temp=dec;
dec=dec.toString().split('.')[1];
frac=Math.pow(10,dec.length)/parseFloat(dec);
obj.firstChild.nodeValue='the decimal='+temp+', the equivalent fraction=1/'+frac;
}
if(window.addEventListener){
window.addEventListener('load',init,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',init);
}
}
function init(){
df=document.forms[0];
obj=document.getElementById('fraction');
df[1].onclick=function() {
decfrac(document.forms[0][0].value);
}
df[2].onclick=function() {
obj.firstChild.nodeValue='';
}
}
</script>
</head>
<body>
<form action="#">
<div>
<label>decimal : <input type="text" value='0.'></label>
<input type="button" value="convert to fraction">
<input type="reset" value="clear result">
</div>
</form>
<div id="fraction"> </div>
</body>
</html>
function decimalPlaces(num) {
var decimalSeparator = '.',
tmp = num.toString(),
idx = tmp.indexOf(decimalSeparator);
if (idx >= 0) {
return (tmp.length - idx - 1);
}
return 0;
}
function decfrac(DtF) {
var n = decimalPlaces(DtF), // the number of decimals
m = Math.pow(10,n), // 10^n
numerator = DtF * m,
denominator = (numerator == 0 ? 0 : m / numerator);
numerator = (numerator == 0 ? 0 : numerator/numerator);
return (numerator == 0 ? "0" : numerator + "/" + denominator);
}
function fractional_part(input,output) {
if (document.getElementById(input) && document.getElementById(output)) {
var inp = document.getElementById(input).value;
if (isNaN(inp)) { alert('Enter a decimal number.'); }
else {
document.getElementById(output).value = decfrac(inp);
}
}
else { alert('Input and output objects not found.'); }
return false;
}
maybe I'm implementing it wrong, seems to give odd results. 1/3 gives 1/3.33333335, but .6 gives 1/1.66666667 (wouldn't 3/5 be more accurate than 2/3?) Seems to work for .5, .25. When whole numbers are included it also does weird stuff (which I guess id trivial, can just split them and tack them back on.)
1/3 is not valid decimal input, it's a fraction.
to the nearest 1/x fraction.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Decimal Numbers to Fraction</title>
<script type="text/javascript">
// input the decimal part, write output to output field
function fractional_part(input,output) {
if (document.getElementById(input) && document.getElementById(output)) {
var inp = document.getElementById(input).value;
if (isNaN(inp) || (inp.indexOf('.')==-1)) { alert('Enter a decimal number.'); }
else {
document.getElementById(output).value = decfrac(inp);
}
}
else { alert('Input and output objects not found.'); }
return false;
}
// Convert decimal to it's simplified fractional part
function decfrac(DtF) {
parts = DtF.split('.');
var decimal = (parts[1])?parts[1]:parts[0];
var whole = (parts[1])?parts[0]:null;
var n = decimal.length;
m = Math.pow(10,n);
g_com_denom=gcd(decimal,m);
fractional = decimal/g_com_denom + '/' + m/g_com_denom;
return (whole)?whole+' '+fractional:fractional;
}
// Get the greatest common denominators of the two parts
// Seems convoluted, but say, for 25 and 100 you get 5*5*5*5 . . .
function gcd(num,denom) {
var gcd=1;
var common_elements = [];
var num_factors=get_factors(num);
var denom_factors=get_factors(denom);
for (w=0;w<num_factors.length;w++) {
var common=0;
for (j=0;j<denom_factors.length;j++) {
if (num_factors[w]==denom_factors[j]) {
common=1;
continue;
}
}
if (common==1) { common_elements.push(num_factors[w]); }
}
for (w=0;w<common_elements.length;w++) {
gcd *= common_elements[w];
}
return gcd;
}
// Get the prime factors for any number
function get_factors(num) {
factors = [];
//var chk='';
var working=num;
var sfactor = 2;
while (sfactor*sfactor <= num) {
if ((working%sfactor == 0) && (working != 1)) {
factors.push(sfactor);
working = working/sfactor;
}
else { sfactor++; }
}
if (working !=1) { factors.push(working); }
return factors;
}
</script>
</head>
<body>
<h1>Decimal Numbers to Fractions</h1>
<form action="" onsubmit="return fractional_part('num','res');">
<p><label for="num">Enter a decimal:</label>
<input type="text" name="num" id="num" size="12" value="">
<input type="submit" value="Get It"><br>
<label for="res">Result:</label>
<input style="border:none;" type="text" name="res" id="res"
size="48" value="" onfocus="this.blur();">
</p>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Decimal Numbers to Fraction</title>
</head>
<body>
<h1>Decimal Numbers to Fractions</h1>
<form action="#" onsubmit="return fractional_part('num','res');">
<div>
<label for="num">Enter a decimal:</label>
<input type="text" name="num" id="num" size="12" value="">
<input type="submit" value="Get It">
<br>
<label for="res">Result:</label>
<input type="text" name="res" id="res" size="24" value="" readonly >
</div>
</form>
<script type="text/javascript">
function decimalPlaces(num) {
var decimalSeparator = '.',
tmp = num.toString(),
idx = tmp.indexOf(decimalSeparator);
if (idx >= 0) {
return (tmp.length - idx - 1);
}
return 0;
}
function decfrac(DtF) {
var i,
j,
gcf,
n = decimalPlaces(DtF), // the number of decimals
m = Math.pow(10,n), // 10^n
numerator = Math.round(DtF * m), // Important to round the result
negative = numerator < 0,
denominator = 1 * (numerator != 0 ? m : 1)
// Save some work if numerator is zero
if (numerator == 0) {
return "0";
}
// Handle negative values
if (negative) {
// Temporarily convert to positive
numerator *= -1; // negative * negative = positive
}
// Get the Greatest Common Factor
for (i = (numerator > denominator ? numerator: denominator); i > 0; i--) {
if ((numerator % i == 0) && (denominator % i == 0)) {
gcf = i;
break;
}
}
numerator = numerator / gcf;
if (negative) {
// Convert back to negative
numerator *= -1;
}
denominator = denominator / gcf;
return numerator + "/" + denominator;
}
/**
* @param {String} input The id of the element containing the decimal input
* @param {String} output The id of the element to write the output to
*/
function fractional_part(input, output) {
var elIn = document.getElementById(input),
elOut = document.getElementById(output),
val;
// Some basic validation
if (elIn && elOut) {
val = elIn.value;
val = val.replace(/^\s+|\s+$/g,""); // trim off whitespace
if (isNaN(val) || val.length == 0) {
alert('Enter a decimal number.');
}
else {
// Do the math
elOut.value = decfrac(val);
}
}
else {
alert('Input and output elements not found.');
}
return false;
}
</script>
</body>
</html>
function decfrac(DtF) {
var i,
j,
gcf,
whole = null,
n = decimalPlaces(DtF), // the number of decimals
m = Math.pow(10,n), // 10^n
numerator = Math.round(DtF * m), // Important to round the result
negative = numerator < 0,
denominator = 1 * (numerator != 0 ? m : 1);
// Save some work if numerator is zero
if (numerator == 0) {
return "0";
}
// Handle negative values
if (negative) {
// Temporarily convert to positive
numerator *= -1; // negative * negative = positive
}
// Get the Greatest Common Factor
for (i = (numerator > denominator ? numerator: denominator); i > 0; i--) {
if ((numerator % i == 0) && (denominator % i == 0)) {
gcf = i;
break;
}
}
if (Math.floor(numerator/denominator) > 0) {
whole=Math.floor(numerator/denominator);
numerator = numerator-(whole*denominator);
}
numerator = numerator / gcf;
if (negative) {
// Convert back to negative
if (whole) { whole *= -1; }
else { numerator *= -1; }
}
denominator = denominator / gcf;
fractional = numerator + "/" + denominator;
return (whole)?whole+' '+fractional:fractional;
}
function decfrac(DtF) {
var i,
j,
gcf,
whole = 0,
n = decimalPlaces(DtF), // the number of decimals
m = Math.pow(10,n), // 10^n
numerator = Math.round(DtF * m), // Important to round the result
negative = numerator < 0,
denominator = 1 * (numerator != 0 ? m : 1)
// Save some work if numerator is zero
if (numerator == 0) {
return "0";
}
// Handle negative values
if (negative) {
// Temporarily convert to positive
numerator *= -1; // negative * negative = positive
}
// Get the Greatest Common Factor
for (i = (numerator > denominator ? numerator: denominator); i > 0; i--) {
if ((numerator % i == 0) && (denominator % i == 0)) {
gcf = i;
break;
}
}
numerator = numerator / gcf;
denominator = denominator / gcf;
if (numerator >= denominator) {
whole = Math.floor(numerator / denominator);
numerator = numerator % denominator;
}
return (negative ? "-" : "") +
(whole > 0 ? whole + " " : "") +
(numerator > 0 ? numerator + "/" + denominator : "");
}