I need a JavaScript function to convert CM to IN. I have been using the following:
function toFeet(n) {
var realFeet = ((n*0.393700) / 12);
var feet = Math.floor(realFeet);
var inches = Math.round(10*((realFeet - feet) * 12)) / 10;
return feet + "′" + inches + '″';
}
console.log(toFeet(100));
The catch is it converts 100cm into 3'3". I only deal in CM (australia) but from checking on conversion sites it appears this is wrong.
Any advice?
Your code is correct and gives the right result.
I would change it in the following way, so I am sure I do not lose precision using an approximate number for the conversion. This may be useless in your case, but sometimes could come into play (e.g. calculating distances on maps).
var realFeet = n / 30.48; // = 12 * 2.54
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With