4

I am trying to convert a string to Integer/Float/Double but I got a NumberFormatException.

My String is 37,78584, Now I am converting this to any of them I got NumberFormatException.

How can I convert this string to any of them.

Please help me to get out of this problem.

Akshay
  • 2,506
  • 4
  • 34
  • 55
Pari
  • 1,705
  • 4
  • 18
  • 19

9 Answers9

12

You have to use the appropriate locale for the number like

String s = "37,78584";
Number number = NumberFormat.getNumberInstance(Locale.FRENCH).parse(s);
double d= number.doubleValue();
System.out.println(d);

prints

37.78584
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Replace , by "" blank in string and then convert your numbers

String str = "37,78584";
str = str.replaceAll("\\,","");
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
  • 1
    Using the proper locale is a better approach. And you need go replace the comma with a period, not a blank. – assylias Sep 11 '12 at 08:17
1

Check the String value

that

if(String .equals(null or ""){

} else{
    //Change to integer
}
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
Anklet.
  • 479
  • 3
  • 14
1

Using methods like Type.parseSomething and Type.valueOf isn't a best choice, because their behavior depends from locale. For example in some languages decimal delimiter is '.' symbol when in other ','. Therefore in some systems code works fine in other it crashes and throw exceptions. The more appropriate way is use formatters. JDK and Android SDK has many ready to use formatters for many purposes which is locale-independent. Have a look at NumberFormat

Dmitriy Tarasov
  • 1,949
  • 20
  • 37
1

The best practice is to use a Locale which uses a comma as the separator, such as French locale:

double d = NumberFormat.getNumberInstance(Locale.FRENCH).parse("37,78584").doubleValue();

The fastest approach is just to substitute any commas with periods.

double d = String.parseDouble("37,78584".replace(",","."));
Charlie-Blake
  • 10,832
  • 13
  • 55
  • 90
0

do this before parsing to remove the commas:

myString.replaceAll(",", "")​;
Deanna
  • 23,876
  • 7
  • 71
  • 156
Vinay W
  • 9,912
  • 8
  • 41
  • 47
0

First Remove , this, using below code

String s= "37,78584";
s=s.replaceAll(",", "");

And then use below code

For String to Integer:-

Integer.parseInt(s);

For String to Float:-

Float.parseFloat(s);

For String to Double:-

Double.parseDouble(s);
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
0

Replace '

String value  = "23,87465";
int value1 = Integer.parseInt(value.toString().replaceAll("[^0-9.]",""));
Pablo Claus
  • 5,886
  • 3
  • 29
  • 38
-1

Try replacing the , and then converting into an Integer/float/double

String mysting="37,78584";
String newString=myString.replace(",", "");
int value=Integer.parseInt(newString);
Deanna
  • 23,876
  • 7
  • 71
  • 156
mukesh
  • 4,140
  • 5
  • 29
  • 40