views:

197

answers:

2

Original question: this bit of javascript code will convert centimeters to feet. But the feet are displayed as decimals, I would like it to display as 5'10 instead of 5.83.

SOLUTION:

<script type="text/javascript">
function start(){
document.getElementById('hauteur_cm').onmouseup=function() {
if(isNaN(this.value)) {
   alert('numbers only!!');
   document.getElementById('hauteur_cm').value='';
   document.getElementById('hauteur_pieds').value='';
   return;
 }
var realFeet = this.value*0.03280839895;
var feet = Math.floor(realFeet);
var inches = Math.round((realFeet - feet) * 12);
var text = feet + "'" + inches + '"';
   document.getElementById('hauteur_pieds').value=text;
  }
 }
if(window.addEventListener){
   window.addEventListener('load',start,false);
 }
else {
if(window.attachEvent){
   window.attachEvent('onload',start);
  }
 }
</script>
A: 
function feetAndInches(decimal) {
  return Math.floor(decimal) +
    "'" +
    (12 * (decimal - Math.floor(decimal))) +
    '"';
}
Pointy
+1  A: 

You can split the decimal feet value into feet and inches like this:

var realFeet = 5.83;

var feet = Math.floor(realFeet);
var inches = Math.round((realFeet - feet) * 12);

Then you can put them together in any format you like:

var text = feet + "'" + inches + '"';
Guffa
pardon me for being such a javascript simpleton but how can I set realFeet to the converted value of "hauteur_pieds" (from code above) and then send the var text to the element ID "hauteur_pieds"? Much appreciated.
dale
@date: First var realFeet = this.value*0.03280839895; then do the conversion and finally use document.getElementById('hauteur_pieds').value = text;
Guffa