Input Value Is a String Instead of a Number

HTML input type=number still returning a string when accessed from javascript

It's normal you get a string.

The purpose of the number type is that mobile browsers use this for showing the right keyboards and some browsers use this for validation purposes. For example the email type will show a keyboard with the @ and '.' on the keyboard and number will show a numeric keyboard.

How can I get a number input value as a number instead of a string?

You can use jQuery's valHooks to change how jQuery returns values.

$.valHooks.number = {
get: function( elem ) {
return elem.value * 1;
}
};

You only need to do this once in your code and then all type=number inputs will instead return a number.

console.log(
"num is a string",
$("#num").val() === "1",
$("#num").val() === 1,
$("#txt").val() === "1",
$("#txt").val() === 1)

$.valHooks.number = {
get: function( elem ) {
return elem.value * 1;
}
};

// confirm no neffect on type='text'
console.log(
"num is a number",
$("#num").val() === "1",
$("#num").val() === 1,
$("#txt").val() === "1",
$("#txt").val() === 1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id='num' value="1">
<input type='text' id='txt' value="1">

Getting a string instead of expected number from Angular template and input native element's value

It is written on the spec that value will always be stored as string. So even if you set the input type as number, it only update the user interface. But the value is still the same in string type.

I don't extract the data the same way with you. Not sure if you have any reason for doing so. I always use the ngModel directive.

Basically it is the two way binding, if you update the data model, it will update the UI and the other way around. So that you don't have to get the value manually through the ElementRef as you did on the question. It is done automatically for you.

app.component.html

<input type="number" [(ngModel)]="inputVal" (keyup)="onKeyUp($event)">

app.component.ts

onKeyUp(event: KeyboardEvent) {    
console.log(this.inputVal);
}

Noted the type="number" on the HTML code. When you set it like that, the inputVal will be return as a number. I didn't really check the source code but probably Angular will parse it automatically somehow.

If you don't put it, the value will still be keep as a string.

I prepare the example for it. Please check https://stackblitz.com/edit/angular-ngmodel-number

You can just type into the input and see the value and the type.

Angular input [type]='number' always results in value being string

This is a known issue (see issue #13243).

A simple workaround for now is to use different inputs for each types :

@Input() public myInputType: string;
<input [(ngModel)]="value" type="number" *ngIf="myInputType === 'number'"/>
<input [(ngModel)]="value" type="text" *ngIf="myInputType === 'text'"/>
<!-- ... -->

In python, if the user enters a string instead of number (integer value) then how can we show message to user that input is invalid?

The simplest way is try/except:

var = input("Enter anything ==>")
try:
if int(var) % 2:
print(f"{var} is an odd number")
else:
print(f"{var} is an even number")
except ValueError:
print(f"{var} is not a number")

If you want to re-prompt the user when they enter something that's not a number, put the whole thing in a while loop and break it when they enter a valid number.

while True:
var = input("Enter anything ==>")
try:
if int(var) % 2:
print(f"{var} is an odd number")
else:
print(f"{var} is an even number")
break
except ValueError:
print(f"{var} is not a number")

My input keeps reading as a string instead of an int how can I solve this issue

You can use the built-in functions int() or float() to return the string as an int or float respectively and where appropriate.

For example:

amount = float(input("Enter amount:"))

Will set amount to a float constructed from the user input.

Other Improvements

Looking at the code you have provided, the other improvements you can make are as follows:

Use // to divide and floor a number.

For example:

hundredDollar = amount // 100

Will set hundredDollar to a whole number indicating the maximum number of times 100 goes into amount. So, if the amount is 150, hundredDollar will be set to 1 as the amount is composed of one whole hundred dollar bill.

Use str() when concatenating a number with a string

When you concatenate (combine) a number with a string and the number comes first, you will need to first cast the number as a string. For example:

str(hundredDollar) + " hundred dollar bills."

When a float is used and you want the output to display as an int i.e. 2 instead of 2.0 then you can either use the int() function or format the output. For example:

print( int(hundredDollar), "hundred dollar bills." ) 

Add validation for user input

When receiving input from the user it is advisable to add some validation to check if the data entered by the user is as expected - in this case, is a valid amount. This can be done using a try and except block for the data type and if statements to check if the data is within a valid range or meets additional requirements.



Related Topics



Leave a reply



Submit