Adam
Adam

Reputation: 20882

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?

Upvotes: 12

Views: 10003

Answers (1)

Francesco Pasa
Francesco Pasa

Reputation: 594

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

Upvotes: 3

Related Questions