Javascript functions for numeric input and output

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.

// 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
// 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;
}

Comments are closed.