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];
Definition and Usage
The toFixed[]
method converts a number to a string.
The toFixed[]
method rounds the string to a specified number of decimals.
Note
If the number of decimals are higher than in the number, zeros are added.
Syntax
Parameters
Parameter | Description |
x | Optional. Number of decimals. Default is 0 [no decimals] |
Return Value
Type | Description |
A string | The representation of a number with [or without] decimals. |
More Examples
Browser Support
Number.constructor
is an ECMAScript3 [ES3] feature.
ES3 [JavaScript 1999] is fully supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |
HTML input type number with decimal precision.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
[function[]{ | |
// Input field given to n decimal places. Degrades gracefully to standard numeric input. | |
// Usage: | |
try { | |
var proto = Object.create[HTMLInputElement.prototype]; | |
proto.createdCallback = function[] { | |
this.type = "number"; | |
this.addEventListener["change", this.decimate]; | |
this.value = parseFloat[this.value].toFixed[this.getAttribute['data-places']]; | |
}; | |
proto.decimate = function[]{ | |
this.value = parseFloat[this.value].toFixed[this.getAttribute['data-places']]; | |
}; | |
document.registerElement["decimal-number", { | |
prototype: proto, | |
extends: 'input' | |
}]; | |
} catch[e]{} | |
}][]; |