-1

I have a case where a user can enter 5.000 or 5.0 and my existing code will output 5.000 regardless, except if you are using Firefox it displays 5. Here is what my code looks like

Util.fixPrecisionCallback = function (precision, keepLeadingZeros) {
    return function (e) {
        var value = $(e.target).val(),
            formatted = Util.formatPrecision(value, precision, keepLeadingZeros);

        if (value !== formatted) {
            e.stopPropagation();
            $(e.target).val(formatted)
        }
    }
};

Util.formatPrecision = function (value, precision, keepLeadingZeros) {

    var fval = parseFloat("" + value);
    fval = isNaN(fval) ? 0 : fval;
    fval = fval.toFixed(precision);

    if (!keepLeadingZeros)
        return fval;

    var leadingZeros = (value.match(Util.LEADING_ZEROS) || []).join("");
    var fvalLeadingZeros = (fval.match(Util.LEADING_ZEROS) || []).join("")

    if (fvalLeadingZeros.length < leadingZeros.length)
    {
        return leadingZeros.substring(0, leadingZeros.length - fvalLeadingZeros.length) + fval; 
    }
    else
    {
        return fval;
    }
};

This is applied on the change event of my input which looks like this

<input type="number" step="any" min="0.100" max="20.000" maxLength="6" id="boxScanLockTimeInput" style="width:160px;" />

_fixPrecision3 = Util.fixPrecisionCallback(3);
$("#boxScanWidthInput", self.displayContainer).on("focusout", function () {
    //stuff
}).on("change", _fixPrecision3);

This same page works fine in Chrome, but for some reason does not work with firefox [no errors, but always displays 5 instead of 5.000]. I have other pages where this boiler plate code works fine on both browsers, but for the life of me I can not find out what is causing this issue.

Surreal
  • 1,007
  • 1
  • 13
  • 29

1 Answers1

2

Firefox is "helping" you by simplifying the number you put in the input box. Remove the type="number" attribute, and it will stop doing that.

And anything else that applies to number inputs, unfortunately.

Some solutions to that problem may be found in How can I make the HTML5 number field display trailing zeroes?.

Martin
  • 348
  • 1
  • 9