Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert to int from String of numbers having comma

Tags:

java

I have value like this:

String x = "10,000";

I want to convert this to int.
I can convert it by removing comma like below:

String y = x.replace(",", "");
int value1 = Integer.parseInt(y);

But I don't want to do it like above.

Any other suggestions like inbuilt function? Or any other recommended ways for this?

like image 592
Ganesh H Avatar asked Jul 22 '14 06:07

Ganesh H


2 Answers

You can simply:

NumberFormat.getNumberInstance(Locale.UK).parse(x);

Read about:

  • NumberFormat
  • Locale.UK and others.
like image 107
Maroun Avatar answered Sep 28 '22 08:09

Maroun


Try this:

 NumberFormat format = NumberFormat.getInstance(Locale.US);    
 Number number = format.parse("10,000"); 

 // Now you can get number values from the object (like int, long, double)
 System.out.println(number.intValue()); 

Output:

10000

Note: If you string contains values after decimal point, you need to use number.doubleValue to retain the precision because number.intValue() will simply ignore values after decimal points.

like image 28
Ankur Shanbhag Avatar answered Sep 28 '22 06:09

Ankur Shanbhag