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 to convert String to Int in Kotlin?
You could call toInt()
on your String
instances:
fun main(args: Array<String>) {
for (str in args) {
try {
val parsedInt = str.toInt()
println("The parsed int is $parsedInt")
} catch (nfe: NumberFormatException) {
// not a valid int
}
}
}
Or toIntOrNull()
as an alternative:
for (str in args) {
val parsedInt = str.toIntOrNull()
if (parsedInt != null) {
println("The parsed int is $parsedInt")
} else {
// not a valid int
}
}
If you don't care about the invalid values, then you could combine toIntOrNull()
with the safe call operator and a scope function, for example:
for (str in args) {
str.toIntOrNull()?.let {
println("The parsed int is $it")
}
}
How to convert string to integer in PowerShell
You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):
$string = "1654"
$integer = [int]$string
$string + 1
# Outputs 16541
$integer + 1
# Outputs 1655
As an example, the following snippet adds, to each object in $fileList
, an IntVal
property with the integer value of the Name
property, then sorts $fileList
on this new property (the default is ascending), takes the last (highest IntVal
) object's IntVal
value, increments it and finally creates a folder named after it:
# For testing purposes
#$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })
# OR
#$fileList = New-Object -TypeName System.Collections.ArrayList
#$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null
$highest = $fileList |
Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } |
Sort-Object IntVal |
Select-Object -Last 1
$newName = $highest.IntVal + 1
New-Item $newName -ItemType Directory
Sort-Object IntVal
is not needed so you can remove it if you prefer.
[int]::MaxValue = 2147483647
so you need to use the [long]
type beyond this value ([long]::MaxValue = 9223372036854775807
).
Short way to convert string to int
my_input = int(my_input)
There is no shorter way than using the int
function (as you mention)
How to convert a string to number in TypeScript?
Exactly like in JavaScript, you can use the parseInt
or parseFloat
functions, or simply use the unary +
operator:
var x = "32";
var y: number = +x;
All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123"
, but will behave differently for various other, possibly expected, cases (like "123.45"
) and corner cases (like null
).
Table taken from this answer
How can I convert a std::string to int?
In C++11 there are some nice new convert functions from std::string
to a number type.
So instead of
atoi( str.c_str() )
you can use
std::stoi( str )
where str
is your number as std::string
.
There are version for all flavours of numbers:long stol(string)
, float stof(string)
, double stod(string)
,...
see http://en.cppreference.com/w/cpp/string/basic_string/stol
Converting string to int and then back to string
It's all about the priority of the actions:
int.Parse (str_Val + 1)
In the row above first the addition happens str_Val + 1
outputing 11
,111
,111
etc.
Then the parsing occurs changing "11"
to 11
Then to string occurs changing 11
to "11"
So change your code to
str_Val = (int.Parse(str_Val)+1).ToString();
This will first convert the string to int, then add two integers and finally convert the integer to string again.
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";
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");
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"));
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)
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.
Related Topics
Why Are Mutable Structs "Evil"
Fastest Way of Inserting in Entity Framework
Issue With Dependencyproperty Binding
Encrypting & Decrypting a String in C#
How to Dynamically Create a Class
How to Check If a Number Is a Power of 2
Find and Extract a Number from a String
How to Ignore a Property in Class If Null, Using Json.Net
Excel "External Table Is Not in the Expected Format."
Deserialize Json into C# Dynamic Object
How to Create a Custom Authorizeattribute in ASP.NET Core
How to Convert a Column Number (E.G. 127) into an Excel Column (E.G. Aa)
What's the @ in Front of a String in C#
How to Get a Textbox to Only Accept Numeric Input in Wpf
Nullable Types and the Ternary Operator: Why Is '? 10: Null' Forbidden