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 = fe开发者_运维问答et + "'" + inches + '"';
document.getElementById('hauteur_pieds').value=text;
}
}
if(window.addEventListener){
window.addEventListener('load',start,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',start);
}
}
</script>
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 + '"';
function feetAndInches(decimal) {
return Math.floor(decimal) +
"'" +
(12 * (decimal - Math.floor(decimal))) +
'"';
}
精彩评论