Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-18-2009, 12:39 AM   PM User | #1
macleodjb
Regular Coder

 
Join Date: Apr 2007
Posts: 317
Thanks: 24
Thanked 3 Times in 3 Posts
macleodjb is on a distinguished road
Converting Decimals to Fractions

I know this is a rather odd post but I need to be able to convert a decimal to a fraction.

Really all i need to know to get what i have to work is being able to tell if a number is whole or not.

For instance if i have an accuracy set of .0625 = 1/16"

If i take my variable which is set to .5625 (9/16")

so if i take variable/accuracy in this case would equal 9. So this way i would know that the numerator would be 9 and my denominator would be 16.

If i take the same accuracy of 1/16 and now introduce a variable of 0.5 then it will give me a remainder.

I think i'm getting all jumbled up, if anyone has any insight this would be great.
macleodjb is offline   Reply With Quote
Old 07-18-2009, 02:58 AM   PM User | #2
venegal
Gütkodierer


 
Join Date: Apr 2009
Posts: 2,127
Thanks: 1
Thanked 426 Times in 424 Posts
venegal has a spectacular aura aboutvenegal has a spectacular aura about
Your post would be less odd if you described what you are actually trying to accomplish, and especially why.

But since for now that post is all there is, I'll try to get into that mumbo jumbo:

Quote:
I know this is a rather odd post but I need to be able to convert a decimal to a fraction.
If that's all you want to do, that's quite easy. .5625 as a fraction is 5625/10000. If you want it in lowest terms, use the euclidian algorithm to compute the greatest common divisor.

Quote:
Really all i need to know to get what i have to work is being able to tell if a number is whole or not.
If that's all you want to know, that's quite easy too.
number == parseInt(number) will tell you if it's whole.

Quote:
For instance if i have an accuracy set of .0625 = 1/16"
If i take my variable which is set to .5625 (9/16")
so if i take variable/accuracy in this case would equal 9. So this way i would know that the numerator would be 9 and my denominator would be 16.
Don't know what you are doing there. You won't know your denominator would be 16; you put that information right into that calculation. You don't want to test all natural numbers just to find out the denominator, do you?

Quote:
If i take the same accuracy of 1/16 and now introduce a variable of 0.5 then it will give me a remainder.
What remainder are you talking about? It will give you 8.

Quote:
I think i'm getting all jumbled up, if anyone has any insight this would be great.
I'm afraid insight into your problem is exactly what I am lacking. Please provide.
venegal is offline   Reply With Quote
Old 07-18-2009, 03:26 AM   PM User | #3
macleodjb
Regular Coder

 
Join Date: Apr 2007
Posts: 317
Thanks: 24
Thanked 3 Times in 3 Posts
macleodjb is on a distinguished road
I'm trying to take a given number whether it be .5625 or .3125 or .5 and convert it to an english fractional number such as 9/16, 5/16, or 1/2"

The user can also specify the accuracy for rounding purposes for the number. which was what i was talking about before if the user wants numbers rounded to the nearest 1/16" of an inch or nearest 1/4" I'm going to try what you've wrote already and see if it helps.

Thanks.
macleodjb is offline   Reply With Quote
Old 07-18-2009, 04:45 AM   PM User | #4
jkd
Senior Coder

 
jkd's Avatar
 
Join Date: May 2002
Location: metro DC
Posts: 3,163
Thanks: 1
Thanked 18 Times in 18 Posts
jkd will become famous soon enough
Well, just multiply by 16 and round to the nearest integer. That gives you the numerator. 16 would, of course, be the denominator.
__________________
jasonkarldavis.com
jkd is offline   Reply With Quote
Old 07-18-2009, 08:27 AM   PM User | #5
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,105
Thanks: 197
Thanked 2,422 Times in 2,400 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Try this:-

Code:
<html>
<head>

<script type="text/javascript">

var roundTo = 16;  // round to nearest 1/roundTo;

function fraction() {
var decimal = document.getElementById('dec').value;
if ((!/^\d*\.\d+$/g.test(decimal)) || (String(decimal).split('.')[1].length > 4)) {
alert ("You must enter a decimal number (max 4 decimal digits)!");
document.getElementById('dec').value = "";
document.getElementById('dec').focus();
return false;
} 
var whole = String(decimal).split('.')[0];
decimal = parseFloat("." + String(decimal).split('.')[1]);
var num = "1";
for (var z=0; z<String(decimal).length-2; z++){
num += "0";
}
decimal = parseInt(decimal*num);
num = parseInt(num);
for (z=2; z<decimal+1; z++) {
if (decimal%z==0 && num%z==0) {
decimal = decimal/z;
num = num/z;
z = 2;
}
}
var result = ((whole==0)?"" : whole+" ") + decimal + "/" + num;

alert ("Fractional value = " + result);

var d = num/roundTo;
var n = Math.round(decimal/d);
alert ("Rounded to nearest 1/" + roundTo + " inch = " + ((whole==0)?"" : whole+" ") + n + "/" + roundTo + " inch");

var HCF = 1;
for (z=1; z<100; z++){
if (n%z == 0 && roundTo%z == 0) {
HCF = z;
}
}
var inch = " inch";
var simplified = (n/HCF +'/'+ roundTo/HCF);
if (simplified == "1/1") {
simplified = "";
whole ++;
}
else if (simplified == "0/1") {
simplified = "";
}
if (whole == 1) {inch = "inch"}
else {inch = "inches"}
if (!whole) {inch = "0 inches"}

alert ("Simplified to: " + ((whole==0)?"" : whole + " ") + simplified + inch);

}

</script>

</head>

<body>
<input type="text" name="dec" id= "dec" size="6" >
<button onclick = 'fraction();'>Change decimal to fraction</button>
</body>
</html>


111,111,111 x 111,111,111 = 12,345,678,987,654,321

Last edited by Philip M; 07-18-2009 at 01:01 PM.. Reason: Improved
Philip M is offline   Reply With Quote
Old 07-18-2009, 10:39 PM   PM User | #6
12 Pack Mack
Banned

 
Join Date: Mar 2009
Posts: 248
Thanks: 3
Thanked 68 Times in 66 Posts
12 Pack Mack is an unknown quantity at this point
macleodjb:

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>None</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">	

	function calcResult(nForm){

		var nMeasurement = nForm['measurement'].value;
		var roundingFraction = nForm['roundTo'].value;
		if (!/^\.\d+$/.test(nMeasurement))
			{
			 alert('Invalid Measurement');
			 nForm['result'].value = "";
			 return;
			}
		if(!/^1\/\d{1,2}$/.test(roundingFraction))
			{
			 alert('Invalid Rounding Fraction');
			 nForm['result'].value = "";
			 return;
			}
		var nMeasureNumerator = nMeasurement.substring(1,nMeasurement.length);
		var nMeasureDenominator = Math.pow(10,nMeasureNumerator.length);		
		var roundingFractionDenominator = roundingFraction.split("/")[1];
		var roundingFractionNumerator =  Math.round((nMeasureNumerator * roundingFractionDenominator) / nMeasureDenominator);
		while (roundingFractionNumerator % 2 == 0 && roundingFractionDenominator % 2 == 0)
			{
			 roundingFractionNumerator = roundingFractionNumerator / 2;
			 roundingFractionDenominator = roundingFractionDenominator / 2;
			}
		while (roundingFractionNumerator % 3 == 0 && roundingFractionDenominator % 3 == 0)
			{
			 roundingFractionNumerator = roundingFractionNumerator / 3;
			 roundingFractionDenominator = roundingFractionDenominator / 3;
			}
		nForm['result'].value = roundingFractionNumerator +  "/" + roundingFractionDenominator;
	}

	function init(){

		var nForm = document.forms[0];
		nForm['convert'].onclick = function()
			{
			 calcResult(nForm);
			}		
	}

	navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);	

</script>
<style type="text/css">

	.center {text-align: center;}

</style>
</head>
	<body>
		<form action="" method="post">
		  
			<label>Decimal Measurement: <input type="text" name="measurement" class="center" size="12" value=".5625"></label>
			<br><br>
			<label>Round to Nearest: <input type="text" name="roundTo" class="center" size="5" value="1/16"></label>
			<br><br>
			<label>Result: <input type="text" name="result" class="center" size="5" readonly></label>
			<br><br>
			<input type="button" value="Convert" name="convert">
			
		</form>
	</body>
</html>

Last edited by 12 Pack Mack; 07-19-2009 at 01:39 PM..
12 Pack Mack is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:06 PM.


Advertisement
Log in to turn off these ads.