As a part of a calculator for model railroad stub switches, I developed a couple of javascript routines for input and output that allow more flexibility than the standard implementation.

This function converts to text for display from a numeric **value**, with a variable number of **decimals,** removing extra trailing zeroes. It also converts the (default inch) measure to millimeters based on the **units** global variable.

1 2 3 4 5 6 7 8 9 10 11 12 |
// Smarter formatting function value, decimals function toVariable(v, d) { if (units == "mm") v = v * 25.4; var r = v.toFixed(d).replace(/0+$/g, ''); if (r.substring(r.length - 1) == '.') { r = r.substring(0, r.length - 1); } return r; } |

This function accepts text from an input box in various formats and units of measurement. The return value is always converted into inches.

Value formats:

- Decimal: a value such as 1.5
- Mixed fraction: a value such as 1 1/2
- Fraction: a value such as 3/8
- Decimal: a value such as 0.375

Measure specifiers:

- in: inches
- ft: feet
- mm: millimeter
- cm: centimeter

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
// Parse a measurement in mm, cm, in or ft // Always returns the value converted to inches function parseMeasure(text) { // Mixed ex: 1 1/2 in var re = /(\d+)\s+(\d+)\/(\d+)\s*(mm|cm|in|ft)?\.?/; var matches = text.match(re); var value; var num, den; var measure; if (matches && matches.length > 0) { value = matches[1]; num = matches[2]; den = matches[3]; measure = (matches.length > 4 ? matches[4] : "in"); } else { // Fraction ex: 1/2 in re = /(\d+)\/(\d+)\s*(mm|cm|in|ft)?\.?/; matches = text.match(re); if (matches && matches.length > 0) { value = "0"; num = matches[1]; den = matches[2]; measure = (matches.length > 3 ? matches[3] : "in"); } else { // Decimal ex: 1.5 in re = /(\d+\.?\d*)\s*(mm|cm|in|ft)?\.?/; matches = text.match(re); var value = (matches.length > 1 ? matches[1] : "0"); var measure = (matches.length > 2 ? matches[2] : "in"); } } // Add the fraction part, if any var x = parseFloat(value); if (num && den) { x = x + parseFloat(num) / parseFloat(den); } // Convert to inches var r = x; switch (measure) { case "mm": r = x / 25.4; break; case "cm": r = x / 2.54; break; case "in": r = x; break; case "ft": r = x * 12; break; } return r; } |