Remove leading zeros from input type=number
Asked Answered
K

7

53

I noticed that if i use <input type="number" /> the leading zeros are not removed. I also saw a lot of discussion on how keeping leading zeros.

For example "000023" and "23" are the same number and i think that it doesn't make sense keeping those zeros.

Kodiak answered 3/6, 2015 at 16:48 Comment(3)
What is it you are trying to actually do?Komsomolsk
Because i have an input that contains an amount, so is better to display it without leading zeros.Kodiak
And what is the problem you face? How to remove the leading zeros or questioning whether it is sensible to leave the leading zeros in the display?Komsomolsk
B
20

just use a regular expression like this

textboxText= textboxText.replace(/^0+/, '')
Botulism answered 3/6, 2015 at 16:54 Comment(2)
Really, a regular expression? why not something like +'00022'.toString()Komsomolsk
it blocks decimal seperatorFlew
B
68

I'm going to give an example with react usage. It uses state which store the value of the field. But, I think u can replace it with whatever variable you like.

<input type='number' value={Number(this.state.myNumber).toString()}/>

In my case, myNumber stores a year number. This way, the year 2018 (for example) won't be displayed mistakenly as 02018.

Bunker answered 21/7, 2018 at 15:30 Comment(4)
Works like a charm. Also, you don't need to have the Number() part if you're doing any processing that converts it to a number. For example, in mine I am rounding the numbers so I only need this.state.myNumber.toString()Quota
This will not let you input numbers like 24.036 numbers with leading zero after decimal.Rainarainah
This was beautiful until I had to enter 5..7.. then move cursor to the middle, then 0, in order to get 0.507, but thanks!Awning
@RicoRodriquezCollins You can just move the cursor to the front and press ., it will automatically add 0.Antaeus
B
20

just use a regular expression like this

textboxText= textboxText.replace(/^0+/, '')
Botulism answered 3/6, 2015 at 16:54 Comment(2)
Really, a regular expression? why not something like +'00022'.toString()Komsomolsk
it blocks decimal seperatorFlew
P
5

HTML input tags always return text, not numbers, even its content can be coerced into numerical formats, dates, etc...

So next you should convert that input to an actual number format:

parseInt(myNum); // If you expect an integer.
parseFloat(myNum); // If you expect floating point number.
Perpendicular answered 3/6, 2015 at 16:52 Comment(4)
Seems like a lot of effort to get rid of leading zeros from a numeric string. Again, in both cases +'00022'.toString() would workKomsomolsk
Also, it can be unsafe to use parseInt without supplying a radixKomsomolsk
You are implicitly doing the same. "+00002" simply foreces type coercion (that is, call parseInt() in this case) and, additionally, taking more effort to convert it again to string which I figure out, in the best case, it is not intended.Perpendicular
Coercion does not call parseInt. Unlike parseInt, when using + or Number no radix is necessary because the internal number conversion will not parse octal numbers.parseInt: Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal. The following may have an octal result, or it may have a decimal result. Always specify a radix to avoid this unreliable behavior.Komsomolsk
S
1

add step="any" to your input tag. if this does not work on your browser, change type to type="tel"

Spaceless answered 13/2, 2019 at 7:16 Comment(2)
type="tel" still allows for leading zeros, although maybe it's a useful trick to filtering for whole numbers only.Uncoil
I was searching for an answer to DISPLAY leading zero's, or actually, to hold them on input while displaying the nice number input on mobile, seems type="tel" is the way to go!Chokedamp
S
1

The hack I have used when using React is to overtly convert the number into a string.
Use value=myNumber.toString(), instead of value=myNumber.
This is only required if the the input type="number", not when if type="text"`.

If your variable is initialized to null, you can prevent errors by changing falsey values to 0, as in: value=(myNumber || 0).toString().

class inputHours extends React.Component {

    this.state = { hours: 0};

    render() {
      return ( 
              <label>Hours: could show Leading 0's</label>
              <input  type="number" min="0" max="24"
                      value={this.state.hours}
                      onChange={this.onChangeHours}
              />

              <label>Hours: strips leading zeros</label>
              <input type="number" min="0" max="24"
                      value={this.state.hours.toString()}
                      onChange={this.onChangeHours}
              />
      );
    } 

In the first case, even if you strip leading zeros in the onChangeHours handler, force conversion back to an Integer via parseInt(), and call setState() to save the number devoid of leading zeros back to the state object, telling react to re-render, the input field itself does not update to remove any leading zeros.
But this issue only arises when the input type is set to "number".
If it is set to type "text", there are no issues, leading zeros are removed as expected.
In both cases, a console.log() shows that the value stored in state is indeed stripped of leading zeros (a single 0 is allowed as a value.)
even as the input field itself may show extra leading zeros.

My best guess is that internally React sees an integer 0 === 000, so it does not bother to update the display??? But in a text string, '0' != '000', so it knows it must update the rendered field.
Anyway, the overt coersion seems to force the input field to update and re-render correctly.

Update: @bitiset has a more complete answer that takes real numbers (floats, decimal points) into consideration.

If your numeric value will be a floating point number with a decimal, instead of an integer, consider using parseFloat() instead, otherwise zeros following the decimal point may get deleted, causing bugs.

However, if you overtly convert your stored value to a string before "saving" it, instead of relying on implicit coercion at read time, perhaps this issue is avoided?

Slosberg answered 1/11, 2021 at 6:5 Comment(0)
W
0

Try this :

<!DOCTYPE html>
<html>
<body>

<input type="number" id="txtfield" /><button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var myNumber = document.getElementById("txtfield").value;
    document.write(parseInt(myNumber ,10));
}
</script>

</body>
</html>
Wintertime answered 3/6, 2015 at 17:6 Comment(0)
D
0

Just use this property on the input tag

onInput={(e) => {e.target.value = Math.abs(e.target.value);}}
Drippy answered 26/3 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.