String to Double in Java

I have a double number Java application. I need to convert String to Double, but string representation of a number

- divides the decimal part of the number (example 1.5 equiv 6/4)

. - divides groups of three digits (example 1.000.000 eq. 1,000,000)

. How to achieve this conversion of String to Double?

+4
source share
5 answers

Here is one way to solve it using DecimalFormat without worrying about locales.

 import java.text.*; public class Test { public static void main(String[] args) throws ParseException { DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setGroupingSeparator('.'); dfs.setDecimalSeparator(','); DecimalFormat df = new DecimalFormat(); df.setGroupingSize(3); String[] tests = { "15,151.11", "-7,21.3", "8.8" }; for (String test : tests) System.out.printf("\"%s\" -> %f%n", test, df.parseObject(test)); } } 

Output:

 "15,151.11" -> 15151.110000 "-7,21.3" -> -721.300000 "8.8" -> 8.800000 
+5
source

It seems that the German format has a number format.

 Double d = (Double) NumberFormat.getInstance(Locale.GERMAN).parse(s); 
+3
source

Use the parse method in DecimalFormat.

+1
source

You need to get rid of , and replace with . :

 String s = "1000.000,15"; double d = Double.valueOf(s.replaceAll("\\.", "").replaceAll("\\,", ".")); System.out.print(d); 
+1
source

DecimalFormat is your friend.

-1
source

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


All Articles