Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert centimeters to inches using Javascript

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?

like image 786
Adam Avatar asked May 14 '13 10:05

Adam


1 Answers

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
like image 133
Francesco Pasa Avatar answered Oct 19 '22 21:10

Francesco Pasa