Reputation: 1715
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.
Upvotes: 4
Views: 6675
Reputation: 479
Check the String value
that
if(String .equals(null or ""){
} else{
//Change to integer
}
Upvotes: 1
Reputation: 22291
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);
Upvotes: 0
Reputation:
Replace '
String value = "23,87465";
int value1 = Integer.parseInt(value.toString().replaceAll("[^0-9.]",""));
Upvotes: 0
Reputation: 11050
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(",","."));
Upvotes: 1
Reputation: 1969
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
Upvotes: 1
Reputation: 4140
Try replacing the ,
and then converting into an Integer/float/double
String mysting="37,78584";
String newString=myString.replace(",", "");
int value=Integer.parseInt(newString);
Upvotes: -1
Reputation: 10190
do this before parsing to remove the commas:
myString.replaceAll(",", "");
Upvotes: 0
Reputation: 533530
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
Upvotes: 12
Reputation: 16158
Replace ,
by ""
blank in string and then convert your numbers
String str = "37,78584";
str = str.replaceAll("\\,","");
Upvotes: 1