Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string (with leading zero or not) to an integer?

Tags:

javascript

How to convert a string (with leading zero or not) to an integer? For example, '08' to 8.

like image 248
Domspan Avatar asked Feb 08 '11 13:02

Domspan


People also ask

How do I turn a string into an integer?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you remove leading zeros from a string?

The simplest approach to solve the problem is to traverse the string up to the first non-zero character present in the string and store the remaining string starting from that index as the answer. If the entire string is traversed, it means all the characters in the string are '0'.

How do you remove leading zeros from an integer?

The int() method to remove leading zeros in PythonThe first method is the int() method, which converts a string into an integer. While converting, it will automatically remove leading zeros in the string. Note that the string should only contain numbers and no letters, alphabets, or other symbols.

How do you know if a string contains leading zeros?

1) Console. WriteLine("false"); else Console. WriteLine("true"); if the string starts with '0' and if it has more than one character.


2 Answers

There are several ways to convert a string to a number, I prefer to use the unary + operator:

var number = +"08"; // 8

This is the equivalent of writing:

var number = Number("08"); // 8

Unlike parseInt(), when using + or Number() no radix is necessary because the internal number conversion will not parse octal numbers. If you want the parseInt() or parseFloat() methods, it's also pretty simple:

var number = parseInt("08", 10); // 8

parseInt and parseFloat are less reliable for user input because an invalid numeric literal might be considered salvageable by these functions and return an unexpected result. Consider the following:

parseInt("1,000");   // -> 1, not 1000
+"1,000";            // -> NaN, easier to detect when there's a problem

Extra Reading

  • Number() - MDC
  • Converting to number (JavaScript Type-Conversion) - jibbering.com
like image 158
Andy E Avatar answered Oct 20 '22 09:10

Andy E


Use parseInt() with the radix argument. This disables autodetection of the base (leading 0 -> octal, leading 0x -> hex):

var number = parseInt('08', 10);
// number is now 8
like image 38
ThiefMaster Avatar answered Oct 20 '22 09:10

ThiefMaster