Best way to parseDouble with comma as decimal separator?

前端 未结 10 783
暗喜
暗喜 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:57

    As E-Riz points out, NumberFormat.parse(String) parse "1,23abc" as 1.23. To take the entire input we can use:

    public double parseDecimal(String input) throws ParseException{
      NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
      ParsePosition parsePosition = new ParsePosition(0);
      Number number = numberFormat.parse(input, parsePosition);
    
      if(parsePosition.getIndex() != input.length()){
        throw new ParseException("Invalid input", parsePosition.getIndex());
      }
    
      return number.doubleValue();
    }
    

提交回复
热议问题