Cristiano
Cristiano

Reputation: 2909

Make an html number input always display 2 decimal places

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?

Upvotes: 60

Views: 263139

Answers (12)

Coffee Guy
Coffee Guy

Reputation: 1

Here's a shorter alternative inline solution

onchange="$(this).val( $(this).val().toFixed(2) )"

Upvotes: 0

Nageen
Nageen

Reputation: 1759

<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

Upvotes: 0

Julia Jacobs
Julia Jacobs

Reputation: 509

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

Upvotes: 1

Yaro-Maro
Yaro-Maro

Reputation: 51

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/

Upvotes: 0

xinthose
xinthose

Reputation: 3828

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

Upvotes: 2

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

Upvotes: 8

carpetofgreenness
carpetofgreenness

Reputation: 57

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

Upvotes: 4

MC9000
MC9000

Reputation: 2403

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

Upvotes: 4

user1413048
user1413048

Reputation: 233

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

onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"

Upvotes: 22

Groot
Groot

Reputation: 14251

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.

Upvotes: 70

spots
spots

Reputation: 2708

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.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

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.

Upvotes: 2

Related Questions