Strings to Integers

How do I convert a String to an int in Java?

String myString = "1234";
int foo = Integer.parseInt(myString);

If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which you can handle:

int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)

how should I convert string to integer and sum the list?

The str and int data types are immutable, so functions called on them can never modify their values.

Hence the int() function can't modify your i variable in the for-loop nor is it supposed to.

As a result, the int() function is designed to return a new integer, thus you must assign it somewhere or it will be "lost in the void".

I.e.

a = ['1', '2', '3']
total = 0
for i in a:
total = total + int(i)

print(total)

Note that it is great practice to learn these, albeit simple, algorithms for operations on lists, strings etc, but the sum() built-in function is there to be used if your in a rush!

a = ['1', '2', '3']
print(sum([int(i) for i in a]))

N.B. I have also used a list-comprehension here that you may not be familiar with; they are really useful, I suggest learning them.

convert only number strings to integer in python list

Try converting to integer if numeric. For floats convert it blindly and if there is an exception, we can assume its a string.

foo = []
for i in a:
if i.isnumeric():
foo.append(int(i))
else:
try:
foo.append(float(i))
except ValueError:
foo.append(i)

print(foo)

Output:
[2, 3, 44, 22, 'cat', 2.2, -3.4, 'Mountain']

UPDATE
A shorter version of the code would be:

foo = []
for i in a:
try:
foo.append(int(i) if float(i).is_integer() else float(i))
except ValueError:
foo.append(i)

print(foo)

encode a list of strings to integers

A one line solution using numpy:

>>> import numpy as np
>>> l = ["pear", "apple", "pear", "banana"]

>>> [np.where(np.array(list(dict.fromkeys(l)))==e)[0][0]for e in l]
[0, 1, 0, 2]

Convert all strings in a list to int

Given:

xs = ['1', '2', '3']

Use map then list to obtain a list of integers:

list(map(int, xs))

In Python 2, list was unnecessary since map returned a list:

map(int, xs)

converting list of integers ,numerical strings into a integer list

Here's how to do it below I explain with code comments.

def solve(lst):
# Dictionary of words to numbers
NUMBERS_DIC = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90}

# list to be returned
retLst = []
for num in lst:
# if num is an int
if type(num)==int: # type() tells you the type of the variable
retLst.append(num)
# if num is a string that is numeric
elif num.isnumeric():
retLst.append(int(num)) # Turn to int
# if num is a string word such as forty-seven"
else:
# turns "forty-seven" -> ["forty","seven"]
word_values_lst = num.split("-")
val = 0
for word in word_values_lst:
val+=NUMBERS_DIC[word] # Get value from NUMBERS_DIC
retLst.append(val)



# Sort lst
retLst.sort()


return list(set(retLst)) # removes duplicates

lst = [1, 3, '4', '1', 'three', 'eleven', 'forty-seven', '3']
retLst = solve(lst)

print(retLst)

How to convert a string to an integer in JavaScript

The simplest way would be to use the native Number function:

var x = Number("1000")

If that doesn't work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods.

parseInt()

var x = parseInt("1000", 10); // You want to use radix 10
// So you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])

Unary plus

If your string is already in the form of an integer:

var x = +"1000";

floor()

If your string is or might be a float and you want an integer:

var x = Math.floor("1000.01"); // floor() automatically converts string to number

Or, if you're going to be using Math.floor several times:

var floor = Math.floor;
var x = floor("1000.01");

parseFloat()

If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.

var floor = Math.floor;
var x = floor(parseFloat("1000.01"));

round()

Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:

var round = Math.round;
var x = round("1000"); // Equivalent to round("1000", 0)


Related Topics



Leave a reply



Submit