Allow 2 decimal places in <input type="number">

HtmlNumbers

Html Problem Overview


I have a <input type="number"> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.

Basically, I am asking for a price input.

I wanted to avoid doing regex. Is there a way to do it?

<input type="number" required name="price" min="0" value="0" step="any">

Html Solutions


Solution 1 - Html

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.

More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

Solution 2 - Html

If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places

^\d*(\.\d{0,2})?$

For an example, I have found solution below to be fairly reliable

HTML:

<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />

JS / JQuery:

$(document).on('keydown', 'input[pattern]', function(e){
  var input = $(this);
  var oldVal = input.val();
  var regex = new RegExp(input.attr('pattern'), 'g');

  setTimeout(function(){
    var newVal = input.val();
    if(!regex.test(newVal)){
      input.val(oldVal); 
    }
  }, 1);
});

Solution 3 - Html

For currency, I'd suggest:

<div><label>Amount $
    <input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur="
this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red'
"></label></div>

See http://jsfiddle.net/vx3axsk5/1/

The HTML5 properties "step", "min" and "pattern" will be validated when the form is submit, not onblur. You don't need the step if you have a pattern and you don't need a pattern if you have a step. So you could revert back to step="any" with my code since the pattern will validate it anyways.

If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number" it will fallback to type="text". If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.

Solution 4 - Html

Step 1: Hook your HTML number input box to an onchange event

myHTMLNumberInput.onchange = setTwoNumberDecimal;

or in the HTML code

<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />

Step 2: Write the setTwoDecimalPlace method

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(2);
}

You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.

toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer

Solution 5 - Html

Try this for allowing only 2 decimal in input type

<input type="number" step="0.01" class="form-control"  />

Or Use jQuery as suggested by @SamohtVII

$( "#ELEMENTID" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

Solution 6 - Html

I found using jQuery was my best solution.

$( "#my_number_field" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

Solution 7 - Html

I had the same requirement but after checking all these answers I realized there is no inbuilt support to block users from typing a particular number of decimal points. step="0.01" is useful when validating the input for a decimal number but still it will not block users from typing any decimal. In my case, I wanted a solution which will prevent user from entering invalid decimal. So I created my own custom JavaScript function which will enforce user any decimal rule. There is a slight performance issue but for my scenario it is okay to have a very small delay to make sure that user is not typing invalid decimal places. It might be useful for someone who wanted to prevent user from typing invalid decimal value on the input.

You can use this solution with step="0.01" if you want. You can use the below function on your element oninput event. If performance is critical for you, then think to use this on onchange event rather than oninput. And please specify maximum number of decimal places allowed in the input in data-decimal attribute. it can have values from 0 to any number.

function enforceNumberValidation(ele) {
    if ($(ele).data('decimal') != null) {
        // found valid rule for decimal
        var decimal = parseInt($(ele).data('decimal')) || 0;
        var val = $(ele).val();
        if (decimal > 0) {
            var splitVal = val.split('.');
            if (splitVal.length == 2 && splitVal[1].length > decimal) {
                // user entered invalid input
                $(ele).val(splitVal[0] + '.' + splitVal[1].substr(0, decimal));
            }
        } else if (decimal == 0) {
            // do not allow decimal place
            var splitVal = val.split('.');
            if (splitVal.length > 1) {
                // user entered invalid input
                $(ele).val(splitVal[0]); // always trim everything after '.'
            }
        }
    }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" data-decimal="0" oninput="enforceNumberValidation(this)" placeholder="No decimal places" value="" />
<input type="number" data-decimal="2" oninput="enforceNumberValidation(this)" placeholder="2 decimal places" value="" />
<input type="number" data-decimal="5" oninput="enforceNumberValidation(this)" placeholder="5 decimal places" value="" />

I might use RegExp to identify invalid value but I have to revert the change in the input as well. So I decided to not use RegExp.

Solution 8 - Html

I had a strange editing experience with some of these solutions. This seems to work pretty well from a user's perspective (only intervene when necessary):

function handleNumberChanged (e) {
    const fixed = parseFloat(e.target.value).toFixed(2).toString()
    if (fixed.length < parseFloat(e.target.value).toString().length)
      e.target.value = fixed
}

Solution 9 - Html

Only 3 decimal point input value in textbox using Javascript.

<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>

function AllowOnlyAmountAndDot(id, e, decimalbool) {    
    if(decimalbool == true) {   
        var t = id.value;
        var arr = t.split(".");
        var lastVal = arr.pop();
        var arr2 = lastVal.split('');
        if (arr2.length > '2') {
            e.preventDefault();
        } 
    }
}

Solution 10 - Html

  <input type="number" class="form-control" id="price" oninput="validate(this)" placeholder="Enter price" name="price" style="width:50%;">

  var validate = function(e) {
      var t = e.value;
      e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
  }

Solution 11 - Html

Use this code

<input type="number" step="0.01" name="amount" placeholder="0.00">

By default Step value for HTML5 Input elements is step="1".

Solution 12 - Html

You can use this. react hooks

<input
                  type="number"
                  name="price"
                  placeholder="Enter price"
                  step="any"
                  required
                />

Solution 13 - Html

just write

<input type="number" step="0.1" lang="nb">

lang='nb" let you write your decimal numbers with comma or period

Solution 14 - Html

On input:

step="any"
class="two-decimals"

On script:

$(".two-decimals").change(function(){
  this.value = parseFloat(this.value).toFixed(2);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnubteensView Question on Stackoverflow
Solution 1 - HtmlMichael BenjaminView Answer on Stackoverflow
Solution 2 - HtmlWeston GangerView Answer on Stackoverflow
Solution 3 - HtmlUltimaterView Answer on Stackoverflow
Solution 4 - HtmlSachin Sudhakar SonawaneView Answer on Stackoverflow
Solution 5 - HtmlNilesh GajareView Answer on Stackoverflow
Solution 6 - HtmlSamohtVIIView Answer on Stackoverflow
Solution 7 - HtmlAbhilash AugustineView Answer on Stackoverflow
Solution 8 - HtmlTreeAndLeafView Answer on Stackoverflow
Solution 9 - HtmlMalik KhababView Answer on Stackoverflow
Solution 10 - HtmlHussainView Answer on Stackoverflow
Solution 11 - HtmlObaidul HaqueView Answer on Stackoverflow
Solution 12 - Htmladitya gathaniaView Answer on Stackoverflow
Solution 13 - Htmlillustray kingView Answer on Stackoverflow
Solution 14 - HtmlxemasivView Answer on Stackoverflow