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.

1

9 Answers 9

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

String str = "37,78584";
str = str.replaceAll("\\,","");

1 Comment

Using the proper locale is a better approach. And you need go replace the comma with a period, not a blank.
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

Comments

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(",","."));

Comments

1

Check the String value

that

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

} else{
    //Change to integer
}

Comments

0

do this before parsing to remove the commas:

myString.replaceAll(",", "")​;

Comments

0

Replace '

String value  = "23,87465";
int value1 = Integer.parseInt(value.toString().replaceAll("[^0-9.]",""));

Comments

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);

Comments

-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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.