0

I have a function bound to the blur event for a specific class (attached to number type inputs) that is intended to force two decimal places. The following function works in Chrome, but does not work in Firefox.

Code:

/**
 *	Force 2 decimal places for specified inputs
 *
 */
$(document).on('blur', '.to-dec', function() {

  // get value
  var value = $(this).val();

  // no value
  if (!value) return;

  // cast to 2 decimal places
  value = parseFloat(value).toFixed(2);

  // update value
  $(this).val(value);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="to-dec" min="0" step="0.01" required>

If I output value before it is set, I get the expected value (ie. 3.00 for an input value of 3).

Anyone know why Firefox would be preventing this value to be set? I've already tried to use parseFloat() when setting the value with val().

Thanks!

2
  • 1
    It looks like Firefox automatically removes insignificant digits in type=number Commented Apr 28, 2017 at 22:20
  • @Barmar Yeah, I just found this bug report from 3 years ago: bugzilla.mozilla.org/show_bug.cgi?id=1003896 Since this issue won't affect my functionality, I think I'll just let it fly. Commented Apr 28, 2017 at 23:01

1 Answer 1

2

An wasy way to make it work in FireFox will be to make the input type "text" and still maintain a type number behaviour with slight modifications to your code, Such as to clear the input if the value is NaN.

$(document).on('blur', '.to-dec', function() {
  // get value
  var value = $(this).val();
  if (isNaN(value)) {
    $(this).val('');
  } else if (!value) {
    // no value
    return;
  } else {
    // cast to 2 decimal places
    value = parseFloat(value).toFixed(2);
    // update value
    $(this).val(value);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="to-dec" min="0" step="0.01">

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I forgot to included the 'required' attribute in my code example. I am verifying the validity of each field on my page whenever fields change to determine whether the user can move on to the next step in the form. I would like to keep the 'number' input type so that the red 'required' border still displays when an invalid value is entered, such as a negative number. However, I could just handle these restrictions in this function too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.