| Decimal to fraction conversion problem
|
Frank_N

msg:4401393 | 10:45 pm on Dec 25, 2011 (gmt 0) | Hi, I'm using the code found here... [webmasterworld.com...] to convert decimals to fractions and it works very well... the problem I'm having is that when there are too many numbers after the decimal it crashes. I'm using this as an input onchange="inch.value = eval(this.value) * 0.03937" and would like to limit the numbers after the decimal to 6. e.g: when entering 10 millimeters the output is 0.39370000000000005 so I'd like to only use 0.393700. Hope it's clear, I have no programming experience what so ever so I apologize in advance if this is trivial. Thanks, Frank
|
birdbrain

msg:4401462 | 11:38 am on Dec 26, 2011 (gmt 0) | Hi there Frank_N, and a warm welcome to these forums. ;) You do not mention which was the code of your choice. :( Here is my code - with the denominator limited to six decimal places... <!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)); if(frac.toFixed(6)!=frac){ temp1=frac=frac.toFixed(6); temp1=parseFloat(temp1); } if(temp1==frac){ frac=temp1; } obj.firstChild.nodeValue='the decimal='+temp+', the equivalent fraction=1/'+frac; } function init(){ var temp1; 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=''; } } window.addEventListener? window.addEventListener('load',init,false): window.attachEvent('onload',init); </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>
|
| birdbrain
|
Frank_N

msg:4401725 | 5:23 pm on Dec 27, 2011 (gmt 0) | Hi Birdbrain, Thanks for the warm welcome and your help :) I'm so new at this I'm not sure what you're asking for lol But here is the code I'm using... hope this helps... // Converts decimals to fractions function decimalPlaces(inch) { var decimalSeparator = '.', tmp = inch.toString(), idx = tmp.indexOf(decimalSeparator); if (idx >= 0) { return (tmp.length - idx - 1); } return 0; } 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 : ""); } 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; } <form action="#" onsubmit="return fractional_part('inch','res');"> <fieldset> <legend>Convert between inches and mm</legend> <table> <tr align="center" valign="middle"> <td>Inches</td> <td> </td> <td>Millimeters</td> <td> </td> </tr> <form> <tr align="center" valign="middle"> <td><input type=text size=12 name="res" value="1" id="res" onchange="return fractional_part('inch','res');" readonly> <input type="text" name="inch" size="12" value="1.000" onchange="milli.value = 25.400 * eval(this.value);" onkeypress='validate(event)'></td> <td>=</td> <td><input type="text" name="milli" size="12" value="25.400" onchange="inch.value = eval(this.value) * 0.03937" onkeypress='validate(event)'> </td> <td><input type="submit" value="Convert"></td> <!--<td><input type="reset" value=" Reset "></td>--> <td> </td> </tr> </form> </table> </fieldset> </form>
|
rocknbil

msg:4402230 | 6:02 pm on Dec 29, 2011 (gmt 0) | Some good reading in understanding the Floating Point Precision [webmasterworld.com] problem and some ways to deal with it.
|
|
|