Converting strings to numbers in JavaScript

preview_player
Показать описание
Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

In this video we will discuss different methods that are available in JavaScript to convert strings to numbers.

This example allows the user to enter 2 numbers and add them. Along the way we will learn the use of the following functions
1. parseInt()
2. parseFloat()
3. isNan()

Here is the HTML for the web form
[table style="border:1px solid black; font-family:Arial"]
[tr]
[td]First Number[/td]
[td][asp:TextBox ID="txtFirstNumber" runat="server"][/asp:TextBox][/td]
[/tr]
[tr]
[td]Second Number[/td]
[td][asp:TextBox ID="txtSecondNumber" runat="server"][/asp:TextBox][/td]
[/tr]
[tr]
[td]Result[/td]
[td][asp:TextBox ID="txtResult" runat="server"][/asp:TextBox][/td]
[/tr]
[tr]
[td]
[/td]
[td]
[input type="button" value="Add" id="btnAdd"/]
[/td]
[/tr]
[/table]

Include the following JavaScript in the head section of the web form.
[script type="text/javascript"]
function addNumbers()
{
}
[/script]

Set the onclick attribute of the Add button to call the addNumbers() function. The HTML for the button should be as shown below.

[input type="button" value="Add" id="btnAdd" onclick="addNumbers()" /]

Run the application and enter 20 as the first number and 10 as the second number. Click Add buton. Notice that JavaScript concatenates the numbers instead of adding them. This is because the value property of the textbox is returning the number in a string format.

So we need to explicitly do the conversion. This is when parseInt() function is useful. Modify the addNumbers() JavaScript function as shown below.
function addNumbers()
{
}

Run the application and test. Notice that we now get 30 as expected.

Let's do another test. Enter 20.5 as the first number and 10.3 as the second number. Click the Add button. Notice that the decimal part is ignored.

To retain the decimal places, use parseFloat() function.
function addNumbers()
{
}

If you leave first number and second number textboxes blank or if you enter text instead of a number, and when you click the Add button, NaN is displayed in result textbox.

NaN in JavaScript stands for Not-a-Number. In JavaScript we have isNaN() function which determines whether a value is an illegal number. This function returns true if the value is not a number, and false if not.

Modify the addNumbers() JavaScript function as shown below.
function addNumbers()
{
if (isNaN(firstNumber))
{
alert("Please enter a valid number in the first number textbox");
return;
}
if (isNaN(secondNumber))
{
alert("Please enter a valid number in the second number textbox");
return;
}
}

Now, when you leave first number and second number textboxes blank or if you enter text instead of a number, and when you click the Add button, you get relevant validation error messages as expected.

Let's make the validation error message a little more relevant:
If the first number and second number textboxes are left blank, then we want to display the following validation messages
a) First Number is required
b) Second Number is required

If you enter text instead of number
a) Please enter a valid number in the first number textbox
b) Please enter a valid number in the second number textbox
Рекомендации по теме
Комментарии
Автор

I seldom comment on youtube...
But, I just have to comment on you..
You have made my life easy...Having gone through BSC IT, lots of things still didnt make sense to me
But as I watch your videos, I wished the teachers had used this to teach me/us, in class...
I wouldn't have needed to be going through all these again.
But thanks for doing all these training videos.
If you want me to give you like or share or anything online, please let me know..
YOU ARE SIMPLY THE BEST

dreigningking
Автор

This type of explanation is mostly required for everyone ❤

LadduLaddu-krjy
Автор

I love your examples because they solve real world problems !

adrianmbugua
Автор

Your explanation is highly simple and this video have been of great help to me.
Thank you so much.

srinivaspagidi
Автор

Now Learning JavaScript.. This playlist Helpful even now..

YusufKhan-itwc
Автор

Your Explanation is highly simplified and simple. Your videos have been of great help to me. keep doing the good job.

oprincesschristy
Автор

Dear Venkat, Thanks for your clear and understandable articles on .Net Technologies, I request you to please post videos on CSS.

shaikibrahim
Автор

Thank you so much .This tutorial is very helpful to me.

ebadrehman
Автор

I love the way you explain your the best teacher

mpauser
Автор

Very great work for giving this useful lectures to us, thanks brother.
please make a series on one complete project with JS oops also, it will be a great help..

shivampandey
Автор

Just out of curiosity (I'm new to JavaScript) why wouldn't you use input type="number" instead of input type="text"?

onee
Автор

in tutorial number 7 you mentioned, we should not place the script file into head tag, but in this example you put the function "addNumber" in head tag. I am kinda confuse .

HashTravel
Автор

Hi Venkat, Thanks for the tutorial. I typed the code in notepad, notepad++ and in Dreamweaver but when I saw the html page in browser it is showing, one table with border and names of the text fields alone. Text fields are not displayed. Why?, will you please help.

saralapuram
Автор

this man is the truth! shout out to all my Indians out there!

Rattus
Автор

I love the way you explain. <3 Thank you :-)

Kaiyoga
Автор

hey venkat, is it possible to convert(nvarchar to nummeric or double) asp:button or boundfield in asp.net with Java Script like in your tutorial? p.s. thx for JS guides again )

Therapyxx
Автор

don't these methods parseFloat and parseInt throw any exception while parsing text ?

ishansharma
Автор

I was doing it in simple forms and after using isNaN function my whole code was not working infact nothing was working afterwards.
Can you suggest me the error ?

ajaykushwaha
Автор

Hello, how we can save a control like textbox in a data base ??

obeid
Автор

what about when we want both int as well as float

yogeshpatil