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")
}
}
Convert string to integer type in Go?
For example strconv.Atoi
.
Code:
package main
import (
"fmt"
"strconv"
)
func main() {
s := "123"
// string to int
i, err := strconv.Atoi(s)
if err != nil {
// ... handle error
panic(err)
}
fmt.Println(s, i)
}
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
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)
Lua string to int
Use the tonumber
function. As in a = tonumber("10")
.
Related Topics
Contentview Not Indenting in iOS 6 Uitableviewcell Prototype Cell
How to Implement a Box or Gaussian Blur on iOS
Does Mkannotationview Buffer Its Input Queue
How to Do a Native "Pulse Effect" Animation on a Uibutton - iOS
Weird Behaviour of Xcode 11 Debugger - Showing Values as Nil When There's a Value
How to Remove Border of the Navigationbar in Swift
Xcode 10, Command Codesign Failed with a Nonzero Exit Code
Creating Thumbnail from Local Video in Swift
Is It Okay to Leave Out Unnecessary Launch Images
iOS 7 Uisearchdisplaycontroller Search Bar Overlaps Status Bar While Searching
Uirefreshcontrol on Uicollectionview Only Works If the Collection Fills the Height of the Container
Centering a View in Its Superview Using Visual Format Language
Massive Memory Leak in iOS Uiwebview
How Come I Can Cast to Nsmanagedobject But Not to My Entity's Type