Best way to parseDouble with comma as decimal separator?

前端 未结 10 603
暗喜
暗喜 2020-11-22 06:14

Following is resulting in an Exception:

String p=\"1,234\";
Double d=Double.valueOf(p); 
System.out.println(d);

Is there a bet

相关标签:
10条回答
  • 2020-11-22 06:58
    Double.parseDouble(p.replace(',','.'))
    

    ...is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.

    Basically replace(char,char) is about 10 times quicker and since you'll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out... Certainly doesn't on my system.

    0 讨论(0)
  • 2020-11-22 06:58

    In Kotlin you can use extensions as below:

    fun String.toDoubleEx() : Double {
       val decimalSymbol = DecimalFormatSymbols.getInstance().decimalSeparator
      return if (decimalSymbol == ',') {
          this.replace(decimalSymbol, '.').toDouble()
      } else {
          this.toDouble()
      }
    }
    

    and you can use it everywhere in your code like this:

    val myNumber1 = "5,2"
    val myNumber2 = "6.7"
    
    val myNum1 = myNumber1.toDoubleEx()
    val myNum2 = myNumber2.toDoubleEx()
    

    It is easy and universal!

    0 讨论(0)
  • 2020-11-22 07:01

    This would do the job:

    Double.parseDouble(p.replace(',','.')); 
    
    0 讨论(0)
  • 2020-11-22 07:05

    This is the static method I use in my own code:

    public static double sGetDecimalStringAnyLocaleAsDouble (String value) {
    
        if (value == null) {
            Log.e("CORE", "Null value!");
            return 0.0;
        }
    
        Locale theLocale = Locale.getDefault();
        NumberFormat numberFormat = DecimalFormat.getInstance(theLocale);
        Number theNumber;
        try {
            theNumber = numberFormat.parse(value);
            return theNumber.doubleValue();
        } catch (ParseException e) {
            // The string value might be either 99.99 or 99,99, depending on Locale.
            // We can deal with this safely, by forcing to be a point for the decimal separator, and then using Double.valueOf ...
            //http://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator
            String valueWithDot = value.replaceAll(",",".");
    
            try {
              return Double.valueOf(valueWithDot);
            } catch (NumberFormatException e2)  {
                // This happens if we're trying (say) to parse a string that isn't a number, as though it were a number!
                // If this happens, it should only be due to application logic problems.
                // In this case, the safest thing to do is return 0, having first fired-off a log warning.
                Log.w("CORE", "Warning: Value is not a number" + value);
                return 0.0;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题