| | 1 | // License: GPL. For details, see LICENSE file. |
| | 2 | package org.openstreetmap.josm.tools; |
| | 3 | |
| | 4 | public class Primitives { |
| | 5 | |
| | 6 | public static double parseDouble(String s) { |
| | 7 | if (s == null) { |
| | 8 | throw new NullPointerException(); |
| | 9 | } |
| | 10 | |
| | 11 | int length = s.length(); |
| | 12 | if (length == 0) { |
| | 13 | throw new NumberFormatException("empty"); |
| | 14 | } |
| | 15 | |
| | 16 | int first = 0; |
| | 17 | int dot = 0; |
| | 18 | long acc = 0; |
| | 19 | long mul = 1; |
| | 20 | |
| | 21 | final char firstChar = s.charAt(0); |
| | 22 | if (firstChar == '-') { |
| | 23 | first = 1; |
| | 24 | mul = -1; |
| | 25 | if (length < 2) { |
| | 26 | throw new NumberFormatException("just sign..."); |
| | 27 | } |
| | 28 | } else if (firstChar == '+') { |
| | 29 | first = 1; |
| | 30 | if (length < 2) { |
| | 31 | throw new NumberFormatException("just sign..."); |
| | 32 | } |
| | 33 | } |
| | 34 | |
| | 35 | for (int i = first; i < length; i++) { |
| | 36 | int ch = s.charAt(i); |
| | 37 | if (ch >= '0' && ch <= '9') { |
| | 38 | acc = acc * 10 + (ch - '0'); |
| | 39 | if (dot > 0) { |
| | 40 | mul *= 10; |
| | 41 | } |
| | 42 | } else if (ch == '.') { |
| | 43 | if (dot > 0) { // second comma |
| | 44 | throw new NumberFormatException("second dot"); |
| | 45 | } |
| | 46 | dot = i; |
| | 47 | } else { |
| | 48 | throw new NumberFormatException("invalid char [" + (char) ch + "]"); |
| | 49 | } |
| | 50 | } |
| | 51 | |
| | 52 | double res = (double) acc / mul; |
| | 53 | |
| | 54 | /* |
| | 55 | double orig = Double.parseDouble(s); |
| | 56 | if (res != orig){ |
| | 57 | throw new NumberFormatException("bad result " + s + " " + res + " " + orig); |
| | 58 | } |
| | 59 | */ |
| | 60 | |
| | 61 | return res; |
| | 62 | } |
| | 63 | } |