Convert String to Integer / Float / Double

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

My String is 37,78584 , now I convert this to any of them, I got a NumberFormatException .

How can I convert this string to any of them.

Please help me out of this problem.

+4
source share
9 answers

You must use the appropriate locale for the number, e.g.

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

prints

 37.78584 
+10
source

Replace with "" space in the line and then convert your numbers

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

Check string value

what

 if(String .equals(null or ""){ } else{ //Change to integer } 
+1
source

Using methods such as Type.parseSomething and Type.valueOf is not a good choice, because their behavior depends on the language. For example, in some languages, the decimal separator is '.' symbol when in another ','. Therefore, in some systems the code works fine, in others it crashes and throws exceptions. A more appropriate way is to use formatters. There are a lot of ready-to-use formatters in the JDK and Android SDK for many purposes that are language-independent. Take a look at NumberFormat

+1
source

Best practice is to use Locale, which uses a comma as a separator, for example, French:

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

The quickest approach is to simply replace any commas with periods.

 double d = String.parseDouble("37,78584".replace(",",".")); 
+1
source

do this before parsing to remove commas:

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

Delete first using the code below

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

And then use below code

For a string with an integer: -

 Integer.parseInt(s); 

For String to Float: -

 Float.parseFloat(s); 

For a double string: -

 Double.parseDouble(s); 
0
source

Replace '

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

Try replacing and then converting to Integer / float / double

 String mysting="37,78584"; String newString=myString.replace(",", ""); int value=Integer.parseInt(newString); 
-1
source

Source: https://habr.com/ru/post/1433537/


All Articles