Display decimal places in feet and inches (javascript)

The original subject: this bit of javascript code converts centimeters to feet. But the legs are displayed as decimal numbers, I would like it to be displayed as 5'10 instead of 5.83.

DECISION:

<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> 
+4
source share
2 answers

You can divide the decimal leg value into legs and inches, like this:

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

Then you can combine them into any format:

 var text = feet + "'" + inches + '"'; 
+6
source
 function feetAndInches(decimal) { return Math.floor(decimal) + "'" + (12 * (decimal - Math.floor(decimal))) + '"'; } 
+1
source

Source: https://habr.com/ru/post/1299341/


All Articles