passsy
passsy

Reputation: 5222

CharSequence to int

Is there a Way to converte a Charsequence or a String to an Ingeter?

CharSequence cs = "123";
int number = (int) cs;

I'm a Noob. Solution:

CharSequence cs = "123";
int number = Integer.parseInt(cs);

Upvotes: 36

Views: 62058

Answers (7)

Joseph Selvaraj
Joseph Selvaraj

Reputation: 2237

From Editview component,

TextView txtYear = (TextView) findViewById(R.id.txtYear);
int intYear = Integer.parseInt(txtYear.getText().toString());

Upvotes: -2

Ajay P. Prajapati
Ajay P. Prajapati

Reputation: 2023

Using Kotlin

CharSeqString.toString.toInt()

Upvotes: 1

Claes Redestad
Claes Redestad

Reputation: 559

Since Java 9 you can use Integer.parseInt(CharSequence s, int from, int to, int radix) to parse integers from any CharSequence without first converting it to a String:

CharSequence cs = new StringBuilder("4711");
int value = Integer.parseInt(cs, 0, cs.length(), 10);

Upvotes: 16

Joachim Sauer
Joachim Sauer

Reputation: 308001

Use Integer.parseInt(). If your CharSequence is not a String, then you need to convert it first using toString().

int number = Integer.parseInt(cs.toString());

Upvotes: 68

Lucas de Oliveira
Lucas de Oliveira

Reputation: 1632

Use the parsers from the Wrapper classes (Integer, Float, etc)...

public static void main(String[] args) {
    String s = "1";
    int i = Integer.parseInt(s);
    System.out.println(i);
}

Upvotes: 0

Kal
Kal

Reputation: 24910

Integer.parseInt(cs.toString())

Upvotes: 1

Sunil Pandey
Sunil Pandey

Reputation: 7102

use this

int i=Integer.parseInt(cs.toString())

Upvotes: 5

Related Questions