Here you can find the source of ParseDoubleEx(String s, double value_if_fault)
Parameter | Description |
---|---|
s | Input string containing the double |
Parameter | Description |
---|---|
ParseException | an exception |
public static double ParseDoubleEx(String s, double value_if_fault)
//package com.java2s; /*/* w w w . ja v a 2 s. co m*/ * Course Generator * Copyright (C) 2016 Pierre Delore * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.text.DecimalFormat; import java.text.ParseException; public class Main { /** * Parse a string containing a double. The separator can be "." or "," * * @param s * Input string containing the double * @return Parsed value in double format * @throws ParseException */ public static double ParseDoubleEx(String s, double value_if_fault) { // throws // ParseException{ int pos, step; double v; String str, s1; boolean ok, error; char decimalseparator = new DecimalFormat().getDecimalFormatSymbols().getDecimalSeparator(); v = 0.0; str = ""; // -- Input string empty s1 = s.trim(); if (s1.isEmpty()) { return value_if_fault; // Return the fault value } // -- Let go ok = true; error = false; step = 0; pos = 0; while ((pos < s1.length()) && (ok) && (!error)) { switch (step) { case 0: { // '+' ou '-' if (s1.charAt(pos) == '+') { str = str + s1.charAt(pos); pos++; } else if (s1.charAt(pos) == '-') { str = str + s1.charAt(pos); pos++; } step = 1; break; } // Case 0 case 1: { // Digit? if (Character.isDigit(s1.charAt(pos))) { str = str + s1.charAt(pos); pos++; } else { // Separator? if ((s1.charAt(pos) == ',') || (s1.charAt(pos) == '.')) { str = str + decimalseparator; pos++; step = 2; } else { error = true; // step = 10; } } break; } // Case 1 case 2: { // Digit? if (Character.isDigit(s1.charAt(pos))) { str = str + s1.charAt(pos); pos++; } else { error = true; } break; } // Case 2 // case 10: { //Error // error=true; // ok=false; // break; // } } // Case } // While if (error) v = value_if_fault; else { // -- Convert the string to double try { DecimalFormat decimalFormat = new DecimalFormat("#"); v = decimalFormat.parse(str).doubleValue(); } catch (ParseException e) { // A problem! set the "fault" value v = value_if_fault; } } return v; } }