56

I'm making a form where the user can enter a dollar amount using an html number input tag. Is there a way to have the input box always display 2 decimal places?

Cristiano
  • 2,839
  • 8
  • 25
  • 35

11 Answers11

68

So if someone else stumbles upon this here is a JavaScript solution to this problem:

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

myHTMLNumberInput.onchange = setTwoNumberDecimal;

or in the html code if you so prefer

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

By changing the '2' in toFixed you can get more or less decimal places if you so prefer.

Groot
  • 13,943
  • 6
  • 61
  • 72
21

an inline solution combines Groot and Ivaylo suggestions in the format below:

onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"
user1413048
  • 223
  • 3
  • 7
  • 2
    This is not working, becouse if you have a placeholder it will take by default that value and you can't change it in input. – Radu Lozovanu Apr 20 '16 at 14:42
  • Actually, even with the placeholder, this works on Google Chrome and Microsoft Edge, tested. Doesn't work on Firefox – eduardo a Feb 27 '19 at 17:23
8

An even simpler solution would be this (IF you are targeting ALL number inputs in a particular form):

//limit number input decimal places to two
$(':input[type="number"]').change(function(){
     this.value = parseFloat(this.value).toFixed(2);
});
  • Nice solution, anyway, that doesn't work with Firefox (version 70.0.1). :/ As a suggestion, I would use a CSS class to distinct the input numbers who get affected by that behaviour (i.e. `:input[type="number"].with-cents`). – Jacopo Pace Nov 07 '19 at 21:44
4

The accepted solution here is incorrect. Try this in the HTML:

onchange="setTwoNumberDecimal(this)" 

and the function to look like:

 function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(2);
    };
MC9000
  • 2,076
  • 7
  • 45
  • 80
4

What other folks posted here mainly worked, but using onchange doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput. My code (mainly borrowing from MC9000):

HTML

<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">

JS

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

Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • I'm saving it with a backbone model that uses a float for this data, so thats not the problem. I just want to have the number displayed in the text box have two decimal places. – Cristiano Feb 13 '13 at 20:29
  • Nevermind, I misunderstood what you were saying... it shall be done this weigh – Cristiano Feb 13 '13 at 20:35
2

You can use Telerik's numerictextbox for a lot of functionality:

<input id="account_rate" data-role="numerictextbox" data-format="#.00" data-min="0.01" data-max="100" data-decimals="2" data-spinners="false" data-bind="value: account_rate_value" onchange="APP.models.rates.buttons_state(true);" />

The core code is free to download

xinthose
  • 3,213
  • 3
  • 40
  • 59
1

Look into toFixed for Javascript numbers. You could write an onChange function for your number field that calls toFixed on the input and sets the new value.

spots
  • 2,483
  • 5
  • 23
  • 38
1

I used @carpetofgreenness's answer in which you listen for input event instead of change as in the accepted one, but discovered that in any case deleting characters isn't handled properly.

Let's say we've got an input with the value of "0.25". The user hits "Backspace", the value turns into "0.20", and it appears impossible to delete any more characters, because "0" is always added at the end by the function.

To take care of that, I added a guard clause for when the user deletes a character:

if (e.inputType == "deleteContentBackward") {
  return;
}

This fixes the bug, but there's still one extra thing to cover - now when the user hits "Backspace" the value "0.25" changes to "0.2", but we still need the two digits to be present in the input when we leave it. To do that we can listen for the blur event and attach the same callback to it.

I ended up with this solution:

const setTwoNumberDecimal = (el) => {
  el.value = parseFloat(el.value).toFixed(2);
};

const handleInput = (e) => {
  if (e.inputType == "deleteContentBackward") {
    return;
  }
  setTwoNumberDecimal(e.target);
};

const handleBlur = (e) => {
  if (e.target.value !== "") {
    setTwoNumberDecimal(e.target);
  }
};

myHTMLNumberInput.addEventListener("input", handleInput);
myHTMLNumberInput.addEventListener("blur", handleBlur);
Julia Jacobs
  • 469
  • 4
  • 7
0

What I didn't like about all these solutions, is that they only work when a form is submitted or input field is blurred. I wanted Javascript to just prevent me from even typing more than two decimal places.

I've found the perfect solution for this:

<!DOCTYPE html>
<html>
<head>

    <script>

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

    <p> Enter the number</p>
    <input type="text" id="resultText" oninput="validate(this)" />

</body>

https://tutorial.eyehunts.com/js/javascript-limit-input-to-2-decimal-places-restrict-input-example/

Yaro-Maro
  • 51
  • 4
0
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>


<input type="text" class = 'item_price' name="price" min="1.00" placeholder="Enter Price" value="{{ old('price') }}" step="">

<script> 
$(document).ready(function() {
    $('.item_price').mask('00000.00', { reverse: true });
});
</script>

give out is 99999.99

nageen nayak
  • 1,262
  • 2
  • 18
  • 28