'Number Input - Step Attribute - format value to 2 decimal places
I am creating a currency input and I want my counter to be able to go up in pence, however, I currently have an issue:
at the moment when I click the step, I get something like 0.38, 0.39, 0.4, 0.41, 0.42
I would want the "0.4" to actually be 0.40, but im unsure how i manage this, would anyone be able to help?
Solution 1:[1]
<input type="number" step="0.10" value="10"></input>
You can use HTML5's step attribute to increment by the particular decimal.
Solution 2:[2]
Listen for the input event and format the input's value accordingly.
document.getElementById('myInput').addEventListener('input', ({target}) => {
target.value = Number(target.value).toFixed(2);
});
<input id="myInput" type="number" step="0.01" value="0.00" />
The toFixed method was made for this, but it's only available on numbers. We infer a number from the current (string) value with Number() then format it to 2 decimal places using toFixed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sanjeev Shakya |
| Solution 2 |
