-4

I'm looking for a short and elegance solution, such as some method.

If it's possible to use method like this:

public Double getDoubleFromString(String string); (inside this method it's needed to get current locale because of different GroupingSeparator and DecimalSeparator in different locales)

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Volodymyr T
  • 102
  • 9
  • what do you mean by `(inside this method it's needed to get current locale because of different GroupingSeparator and DecimalSeparator in different locales)`?? – Blu Feb 20 '20 at 11:03
  • For example, the string 1,255,000,000 is parsed to 1255000000 in US locale, and to 1.255 in DE(Germany) locale. Decimal point are different in different countries (locales) such as "." and ",". Java operate with Double by using "." as decimal point. – Volodymyr T Feb 20 '20 at 11:06
  • 1
    https://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator something of this sort might help you. – Bhavik Shah Feb 20 '20 at 11:07
  • Bhavik Shah, in solving my question, I used the information from your link. – Volodymyr T Feb 20 '20 at 11:45

2 Answers2

0

You should be avoiding double precision by using BigDecimal. Would this work in your case (kotlin) ?

        val formatter: NumberFormat = DecimalFormat.getInstance()
        (formatter as DecimalFormat).isParseBigDecimal = true

        Log.d("test","${formatter.parse("value to parse")?.toDouble()}" )

Some results:

en-us: "123,56.2498" -> 12356.2498
en-us: "123abc" -> 123.0
ua-uk: "123,56.2498" -> 123.56
ror
  • 3,295
  • 1
  • 19
  • 27
0

I found a solution that helped me in my case:

public double getDoubleFromString(String string) {
   NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
   Number number;
   double d;
   try {
      number = format.parse(string);
      d = number.doubleValue();
   } catch (Exception e) {
      e.printStackTrace();
      d = Double.NaN;
   }
   return d;
}

This is what I meant and looked for. Maybe someone will come in handy.

Volodymyr T
  • 102
  • 9