JavaScript Convert String to Number

收藏待读

JavaScript Convert String to Number

This tutorial help to convert string into number in javascript . We will create sample example to convert string data into integer type data.The are different ways to convert string to int in JavaScript.

There are following methods that can be use to convert string into integer –

  • parseInt()
  • unary plus
  • parseFloat()
  • Math.round()
  • Number()

Convert String Into Integer Using parseInt()

parseIntis most popular method to convert string into integer.The parseInt() takes two parameters, The first parameter is the string value and second one the radix. The radix parameter is used to specify which numeral system to be used.

var x = parseInt(「1000」, 10);
//return 1000

The parseInt method get a number from a string and return them.The string must be start with number if not then it will return NAN.

parseInt("hello 1000", 10) //NaN

JavaScript String to Integer Using Number()

The javascript Number() method also help to convert string into number.The number() method takes one argument which is number.

Number('1000') //10000
Number('1,000') //NaN
Number('1000.00') //10

String to int Using Math.floor()

The math package have floor method that convert string into int.The floor() is a static method and return the largest integer less than or equal to the specified number.

Math.floor( 65.95); //  65
Math.floor(-65.08); // -66 

String to int Using Math.round()

The math.round() is a another method that convert string value into integer.The math.round() returns the value of a number rounded to the nearest integer.

Math.round(65.95); //  66
Math.round(65.48); // 65 

String to int Using Unary(+)

You can also use unary(+) operator convert string into integer.Its simplest and easy for data manipulation.A unary operator works on one value. The JavaScript has unary plus (+) , unary minus (-) , prefix / postfix increments (++) , prefix / postfix decrements (–) operator.

var x = +"100" // 10;

相關閱讀

免责声明:本文内容来源于JS-Tutorials,已注明原文出处和链接,文章观点不代表立场,如若侵犯到您的权益,或涉不实谣言,敬请向我们提出检举。