How to Make the HTML5 Number Field Display Trailing Zeroes

How can I make the HTML5 number field display trailing zeroes?

I've had a little play around with this and looked at the spec. It says that it must be a valid floating point number. There's one sentence in the definition of a valid floating point number it gives which caught my attention:

The best representation of the number n as a floating point number is
the string obtained from applying the JavaScript operator ToString to
n.

This means that the format will always be consistent with assessing what the number is, then using JavaScript's toString on that number. So no trailing 0s then.

So, you're going to have to resort to JavaScript. This isn't straightforward because document.getElementById('numInput').value = '0.50'; still gets corrected to 0.5, so the validation isn't triggered at onchange where the default action can be prevented, it's triggered internally.

This is the best solution I could come up with... it's a bit of a hack, and will need a bit of tweaking for robustness, but hopefully it'll do what you want:

var numInput = document.getElementById('numInput');
numInput.addEventListener('keypress', function () {
this.setAttribute('type', 'text');
});
numInput.addEventListener('click', function () {
this.setAttribute('type', 'number');
});

So if the user wants to enter the number by typing, it switches the input type to text, but when they click it, it converts it back to a number.

If you always want the trailing 0s no matter what the user types, then you could do it something like this:

var numInput = document.getElementById('numInput');
numInput.addEventListener('blur', function () {
if (this.value === '') {
return;
}
this.setAttribute('type', 'text');
if (this.value.indexOf('.') === -1) {
this.value = this.value + '.00';
}
while (this.value.indexOf('.') > this.value.length - 3) {
this.value = this.value + '0';
}
});
numInput.addEventListener('focus', function () {
this.setAttribute('type', 'number');
});

Edit: I think the second solution is more inline with what the user might expect, but it means that if the user types 0.5 it will be coerced to 0.50, so it depends if that's what you want.

Show trailing decimal zeroes on HTML number input

You could use a sneaky bit of JavaScript to swap the input between text and number type:

var numInput = document.getElementById('numInput');
numInput.addEventListener('keypress', function () {
this.setAttribute('type', 'text');
});
numInput.addEventListener('click', function () {
this.setAttribute('type', 'number');
});

This is just taken from this really good answer here, it may have other solutions to your problem (although I'm not sure if it works with mobile safari): How can I make the HTML5 number field display trailing zeroes?

how to display trailing zeros in input type number (angular, js)

To achieve expected result, use below of using ng-blur with parseFloat and toFixed

Option 1:

Use ng-blur option to format entered number by parseFloat with toFixed(4)

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $filter) {
$scope.format = function(event, $filter) {
const val = event.target.value;
const decimalCnt = val.split('.')[1] ? val.split('.')[1].length : 0;
event.target.value = decimalCnt && decimalCnt > 4 ? event.target.value : parseFloat(val).toFixed(4)
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="test" ng-blur="format($event)"><br>
</div>

</body>

</html>

Keep trailing or leading zeroes on number

No. A number stores no information about the representation it was entered as, or parsed from. It only relates to its mathematical value. Perhaps reconsider using a string after all.


If i had to guess, it would be that much of the confusion comes from the thought, that numbers, and their textual representations would either be the same thing, or at least tightly coupled, with some kind of bidirectional binding between them. This is not the case.

The representations like 0.1 and 0.10, which you enter in code, are only used to generate a number. They are convenient names, for what you intend to produce, not the resulting value. In this case, they are names for the same number. It has a lot of other aliases, like 0.100, 1e-1, or 10e-2. In the actual value, there is no contained information, about what or where it came from. The conversion is a one-way street.

When displaying a number as text, by default (Number.prototype.toString), javascript uses an algorithm to construct one of the possible representations from a number. This can only use what's available, the number value, also meaning it will produce the same results for two same numbers. This implies, that 0.1 and 0.10 will produce the same result.

Concerning the number1 value, javascript uses IEEE754-2019 float642. When source code is being evaluated3, and a number literal is encountered, the engine will convert the mathematical value the literal represents to a 64bit value, according to IEEE754-2019. This means any information about the original representation in code is lost4.

There is another problem, which is somewhat unrelated to the main topic. Javascript used to have an octal notation, with a prefix of "0". This means, that 003 is being parsed as an octal, and would throw in strict-mode. Similarly, 010 === 8 (or an error in strict-mode), see Why JavaScript treats a number as octal if it has a leading zero

In conclusion, when trying to keep information about some representation for a number (including leading or trailing zeroes, whether it was written as decimal, hexadecimal, and so on), a number is not a good choice. For how to achieve some specific representation other than the default, which doesn't need access to the originally entered text (e.g. pad to some amount of digits), there are many other questions/articles, some of which were already linked.


[1]: Javascript also has BigInt, but while it uses a different format, the reasoning is completely analogous.

[2]: This is a simplification. Engines are allowed to use other formats internally (and do, e.g. to save space/time), as long as they are guaranteed to behave like an IEEE754-2019 float64 in any regard, when observed from javascript.

[3]: E.g. V8 would convert to bytecode earlier than evaluation, already exchanging the literal. The only relevant thing is, that the information is lost, before we could do anything with it.

[4]: Javascript gives the ability to operate on code itself (e.g. Function.prototype.toString), which i will not discuss here much. Parsing the code yourself, and storing the representation, is an option, but has nothing to do with how number works (you would be operating on code, a string). Also, i don't immediately see any sane reason to do so, over alternatives.

Display Leading Zeros On Input Number Fields

You can add an onchange attribute to your input tag, which calls a javascript function.

    <script>
function myFunction() {
var minuteValue = document.getElementById("minutes").value;
if (minuteValue.length < 2) {
minuteValue = "0" + minuteValue;
}
alert(minuteValue);
}
</script>

<input id="minutes" onchange="myFunction()"/>

HTML Input Type Number with Leading Zero on Input

something like this:

function addLeadingZero(event) {
// get maxlength attr
const maxLength = parseInt(event.target.getAttribute("maxlength"))
// "0".repeat(maxLength) <-- create default pad with maxlength given
// append zero and slice last of attr maxlength value
const newValue = ("0".repeat(maxLength) + event.target.value.toString()).slice(-maxLength);
// change the value of input
event.target.value = newValue
}
<!-- @event onkeyup to make sure function run on every key up -->
<!-- @event onchange to make sure function run when we click on arrow up/down -->
<input type="number" maxlength="6" onkeyup="addLeadingZero(event)" onchange="addLeadingZero(event)">

Force leading zero in number input

I'm afraid there is not native HTML way to do that unless using a Select tag. If you are using a text input you have to add the leading 0 on the 10 first values by javascript.



Related Topics



Leave a reply



Submit