Type Conversion

In most website you may need to fill up some forms or give any inputs in the search bar. During this process sometimes you might get errors because of type of the input might string instead of number. In that time, you can use type conversion methods to convert the strings to number.Convert Strings to number

let anyValue = "5";
  • parseInt(anyValue)
  • +anyValue
  • Number(anyValue)

By using any of these methods you can convert a string to number, all works in the same way. You should know all these methods exist because every developer uses their Favourite methods to convert the strings. While working as a JavaScript developer definitely you will together will multiple developers.

In modern codebase mostly you will see this "+" way to convert the strings. But you might see any older tutorials uses reaming two ways to convert.

Convert Decimal Number

While converting decimal number you cannot use any of the above methods because it will round up the number and it will not show the actual decimal value to the user. So you have to use this method

  • parseFloat(anyvalue)

Here you can directly pass any value as "565" or stored any value in let or const and pass the variable name inside the parseFloat(). But keep in mind you should follow the case same as we gave in the example above.

NaN (Not a Number)

Sometimes you might get this of error while trying to convert a number in your code, it means the given input cannot be converted as number. By these methods above mentioned methods will only convert if the number was given as string.

If you try to convert a string contains any characters it cannot be converted to number and you cannot perform any arithmetic operations.

Check the Type of Varible

You can check any Varible type by using typeof method. You might confusion what is method? method is a function which given inside an object. Don't worry we will explain everything about functions, methods, objects and arrays.

Type Coercion

This is an interesting topic and you will be asked about this in interview. When you try to add a number with a string of a number it will concat that those two numbers. But if you try to multiple a number type and string type number you will get the answer of two multiplication.

Example 1:
let number = 2 + "2";
console.log(number)
This will give output as 22 not 4

Example 2:
let number = 4 * "2";
console.log(number)
The output of this will be 8

This will be very useful while getting ID of any product or other data from the database. That time you may need to convert that string to number or convert the number to string based on your requirements.

Post a Comment

أحدث أقدم