Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display feet decimals in feet and inches (javascript)

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>
like image 996
dale Avatar asked Jan 25 '10 17:01

dale


1 Answers

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 + '"';
like image 139
Guffa Avatar answered Oct 07 '22 14:10

Guffa