Results 1 to 2 of 2

Thread: [RESOLVED] Beginner help javascipt cm to inches

  1. #1
    Join Date
    May 2013

    resolved [RESOLVED] Beginner help javascipt cm to inches

    Hi I am learning Javascript online and I have been set a task: User inputs cm into a text field and js returns result in cm with fractions eg 65.5 cm = 25 4/5 inches. I have worked out how to convert cm to inches and separately have
    found a code snippet for converting decimals to fractions which I have changed slightly to suit my needs. Both
    scripts work independent of each other, but when i combine them something I am doing is wrong. Any hints on how
    to combine these scripts into one cm to inch with fractions converter? I really want to try to figure out how to do
    this myself, I'm just a little lost without a teacher to get timely feedback from. Please forgive my clumsy coding

    Script for fraction conversion:

    <script type="text/javascript">
    function fraction(){
    	inches2= 0.8;
    	decimal= inches2;
    	whole = String(decimal).split('.')[0];
    	decimal = parseFloat("."+String(decimal).split('.')[1]);
    	num = "1";
    	for(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;
    	return ((whole==0)?"" : whole+" ")+decimal+"/"+num;
    document.getElementById("result").innerHTML= "fraction()";
    <form name="frm">
    	<fieldset><legend>Convert cm to Inches</legend>
    		<div class="divFrmElement">
            <input type="text" name="T1" id='dec' /> cm  =
            <input type="button" value="Convert" onclick="alert(fraction());" /></div>
    		<div id="result" name="result">Answer Goes Here</div>
    Script for cm to inch conversion:

    <script language="javascript">
    function convfromcmeters(frm) {
    	var cm2;
    	var inches2;
    	var cmeters2;
    		alert("Please enter numbers only");
    		return false;
    	inches2 = ((frm.cmeters2.value) * .393700787).toFixed(1);
    		alert("Please enter valid values into the boxes");
    	w = Math.floor(inches2);
     	k = inches2 % 1;
    	d = k.toFixed(1);
    	return false;

  2. #2
    Join Date
    May 2013
    I worked on it some more and figured it out.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center