HTML:
<input id="feet" type="text" onkeyup="calculate 'feet')" /> ' <input id="inches" type="text" onkeyup="calculate('inches')" /> " <input id="metres" type="text" onkeyup="calculate('metres')" />
JavaScript:
<script type="text/javascript"> function calculate(src) { switch (src) { case feetCtrl: calculateFeetAndInchesToMetres(); break; case inchesCtrl: calculateFeetAndInchesToMetres(); break; case metresCtrl: calculateMetresToFeetAndInches(); break; } } function calculateFeetAndInchesToMetres() { var feet = $get("feet").value; var inches = $get("inches").value; var totalInches = feet * 12; totalInches = totalInches + (inches * 1); var cm = totalInches * 2.54; var metres = cm / 100; $get("metres").value = metres.toFixed(2); } function calculateMetresToFeetAndInches() { var metres = $get("metres").value; var metreInches = metres * 39.370078740157477; $get("feet").value = Math.floor(metreInches / 12); $get("inches").value = Math.floor(metreInches % 12); } </script>
Same functionality in C#
////// Gets the feet and inches representation of a metric value /// /// The metres to use ///The correct display string public static string GetFeetAndInches(double metres) { Hashtable values = GetFeetAndInchesValues(metres); double feet = (double)values["Feet"]; int inches = (int)values["Inches"]; StringBuilder result = new StringBuilder(); string feetText = feet.ToString(); string[] data = feetText.Split('.'); if (data.Length > 0) { feetText = data[0]; } result.Append(feetText); result.Append("'"); if (inches > 0) { result.Append(" "); result.Append(inches); result.Append("\""); } return result.ToString(); } ////// Gets the feet and inches of a metric value /// /// The metres to use ///An array of feet, inches public static Hashtable GetFeetAndInchesValues(double metres) { Hashtable result = new Hashtable(); double metreInches = metres * MetreToInchesRatio; double feet = metreInches / 12; int inches = Convert.ToInt32(metreInches % 12); result.Add("Feet", feet); result.Add("Inches", inches); return result; } ////// Gets the metre equivalent of feet and inches combination /// /// The foot value /// The inches value ///The metre value public static double GetMetresFromFeetAndInches(double feet, int inches) { // Sourced from: http://sg.answers.yahoo.com/question/index?qid=20070403095853AA3FKJZ double totalInches = feet * 12; totalInches += inches; double cm = totalInches * 2.54; double metres = cm / 100; return metres; }
1 comment:
Thanks dude, was doing a meter-to-feet conversion in JS and then realised "But you get 5'11"!"... haha... so googled it and found you page. Helped me out loads !
Post a Comment