Javascript string to number decimal

Learn 9 ways you can convert a string to a number type with JavaScript

When you want a number with floating points, then you can use these functions and operators:

  • Number()
  • parseFloat()
  • The unary + operator
  • The unary — operator
  • Implicit conversion with the minus, multiplication, division, or remainder operator

Let’s see an example of these functions in action next.

Create a rounded number from the string

The parseInt() function parses a value you passed as its argument and tries to return a number that represents that value.

When you pass a string into the function, it will return a whole number as shown below:

Note that strings with floating numbers are always rounded down, even when the floating number is greater than .49 .

You can use the Math.round() method to round the string with floating numbers up or down depending on the floating number’s value:

To always round the floating number down, use the Math.floor() method:

To always round the floating number up, use the Math.ceil() method:

And that’s how you create a rounded number when converting a string into a number.

Next, let’s learn how to convert a string into a number and preserve the floating points.

Create a decimal number from the string

Decimal numbers are numbers with floating points. The native Number() function in JavaScript will convert your string into its number representation without rounding the floating points:

Next, the parseFloat() function is a native JavaScript function to return a floating-point number from a value.

The code below shows how the parseFloat() function works:

When encountering an incorrect number format, the parseFloat() function still tries to return a number that represents the string.

On the other hand, the Number() function immediately returns a NaN when the number format is unrecognized.

The Number() function is more strict than the parseFloat() function.

Besides these two functions, you can also convert a string of decimal numbers using the unary plus ( + ) and minus ( — ) operator.

The + operator evaluates the operand you added next to the operator and tries to return a number as shown below:

Читайте также:  Процесс создания объекта java

The — operator evaluates the given operand and negates the number, creating a negative number in the process:

The code below shows how the — operator works:

And that’s how the — operator can be used to convert a string into a number.

JavaScript implicit type conversion with minus / multiplication / division / remainder operator

JavaScript automatically converts a string into a number when you use an arithmetic operator except for the unary + operator.

Consider the following code examples:

When you use the + operator, JavaScript will concatenate the string and the number instead of converting the string.

In the following code examples, the expressions produce a string instead of a number:

You need to manually convert the string into a number before using the + operator as shown above.

And that’s how you can convert a string into a number in JavaScript.

Depending on the requirements you have in your project, you can use one of the nine ways mentioned in this tutorial.

Thank you for reading. I hope this tutorial has been useful for you. 🙏

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

7 ways to convert a String to Number in JavaScript

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned.
This method has a limitation though. If you parse the decimal number, it will be rounded off to the nearest integer value and that value is converted to string. One might need to use parseFloat() method for literal conversion.

myString = '129' console.log(parseInt(myString)) // expected result: 129 a = 12.22 console.log(parseInt(a)) // expected result: 12 

2. Using Number()

Number() can be used to convert JavaScript variables to numbers. We can use it to convert the string too number.
If the value cannot be converted to a number, NaN is returned.

Number("10"); // returns 10 Number(" 10 "); // returns 10 Number("10.33"); // returns 10.33 

3. Using Unary Operator (+)

The unary plus operator ( + ) precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn’t already.

const x = 25; const y = -25; console.log(+x); // expected output: 25 console.log(+y); // expected output: -25 console.log(+''); // expected output: 0 

4. Using parseFloat()

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned.

parseFloat("10"); // returns 10 parseFloat("10.33"); // returns 10.33 parseFloat("10 20 30"); // returns 10 parseFloat("10 years"); // returns 10 parseFloat("years 10"); // returns NaN 

5. Using Math.floor()

The Math.floor() function returns the largest integer less than or equal to a given number. This can be little tricky with decimal numbers since it will return the value of the nearest integer as Number.

str = '1222' console.log(Math.floor(str)) // returns 1222 a = 12.22 Math.floor(a) // expected result: 12 

6. Multiply with number

Multiplying the string value with the 1 which won’t change the value and also it will be converted to number by default.

str = '2344' console.log(str * 1) // expected result: 2344 

7. Double tilde (~~) Operator

str = '1234' console.log(~~str) // expected result: 1234 negStr = '-234' console.log(~~negStr) // expected result: -234 

Here is the comparison of the ways mentioned performance wise. Comment below if you know more methods.
Thank You

Читайте также:  Javascript вернуть значение анонимной функции

Top comments (17)

The double tilde method is actually something I never thought about, but is worth explaining.

The double tilde «operator» is not as much as an operator as it’s a double bitwise negation.

Let’s cast ’64’ to 64 using this method, so we do ~~’64’ . First we will evaluate ~’64’ . As bitwise operations work on binary, ’64’ is cast to a number. So ~64 .

64 in binary is 01000000 . ~ will negate all the bits so it becomes 10111111 , which is -65 since numbers in JavaScript are signed. Now we negate it again, which becomes 01000000 , which is 64 in decimal.

I previously stated that 10111111 is -63 , which is incorrect. It’s actually -65 . Sorry about that.

14 likes Like Comment button

Источник

How to Convert String to Number in JavaScript

JavaScript provides various methods to convert a string into a number. Let’s turn to their discussion bellow:

1. How to Convert a String into Point Number

Use parseFloat() function, which purses a string and returns a floating point number. The argument of parseFloat must be a string or a string expression. The result of parseFloat is the number whose decimal representation was contained in that string (or the number found at the beginning of the string).

If your string is «384.75a» the result will be 384.75.

Example

w3docs logo

Converting a JavaScript string into a float number

If the string argument cannot be parsed as a number, the result will be NaN (not-a-number value).

w3docs logo

Converting a JavaScript string into a float number

2. How to Convert a String into an Integer

Use parseInt() function, which parses a string and returns an integer.

The first argument of parseInt must be a string. parseInt will return an integer found in the beginning of the string. Remember, that only the first number in the string will be returned.

Читайте также:  Java files размер папки

For example when we have the string “384.75a” and we want to convert it to a number, the result will be 384.

Example

w3docs logo

Converting a JavaScript string into a number

The second argument is radix, it specifies the base of the number whose string representation is contained in the string. The radix, argument can be any integer from 2 to 36. Remember that radix is separated from the string by a comma.

Let’s consider you have the string «77.22», and you set the radix 16. The result will be 119 (= 7 + 7*16).

w3docs logo

Converting a JavaScript string into a number

Strings beginning with 0x or -0x radix are parsed as hexadecimals(the radix is 16) . If you have “0x77” string, the result will be 119 (= 7 + 7*16).

w3docs logo

Converting a JavaScript string into a number

Strings beginning with 0 or -0 are parsed as octal numbers. If you have the string “-077” the result will be -77.

w3docs logo

Converting a JavaScript string into a number

If the first argument cannot be converted to an integer, the result will be NaN .

w3docs logo

Converting a JavaScript string into a number

Note: Despite parseFloat() function, in parseInt() only the first component in the string will return, i.e. if you have 35.22 only 35 will return.

3. How to Convert a String into a Number

Use Number() function, which converts the object argument to a number that represents the object’s value.

Example

w3docs logo

Javascript converts the object argument to a number

The given example will return 384.75

Note: Despite parseFloat() and parseInt(), Number() function returns NaN if the string contains any text.

4. How to Use + Before a String

One trick is to use + before the string:

Example

w3docs logo

Javascript use + before the string

The result of the above-mentioned example will be 384.75.

Note: If you put a comma (,) instead of a dot (.) the result will be NaN, because the string will not be a number.

5. How to Use * 1 After a String

Use * 1 after the string

This is one of the fastest options, it is similar to the + unary operator. It does not perform conversion to an integer if the number is a float.

Example

w3docs logo

Javascript the + unary operator

Recommendation: If you change the number 1 into any other number, it will multiply the number of the string. If you put 0, the result will be 0.

Example of padStart() method

The padStart() method is a built-in function in JavaScript that allows you to pad a string with another string until it reaches a specified length.

In this example, x is a number and xString is a string that represents x with a minimum of two digits. The toString() method converts the number x to a string, and the padStart() method pads the resulting string with leading zeros to ensure that it has at least two digits.

Источник

Оцените статью