Skip to content
This repository was archived by the owner on Dec 29, 2018. It is now read-only.

Commit a5cbc6d

Browse files
authored
Merge pull request #88 from barrypress/double-from-string
Simplified double string parsing
2 parents ecb7bb0 + 995099d commit a5cbc6d

File tree

3 files changed

+6
-36
lines changed

3 files changed

+6
-36
lines changed

.DS_Store

6 KB
Binary file not shown.

CommandLineKit/StringExtensions.swift

Lines changed: 4 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -43,40 +43,10 @@ internal extension String {
4343
* - returns: A Double if the string can be parsed, nil otherwise.
4444
*/
4545
func toDouble() -> Double? {
46-
var characteristic: String = "0"
47-
var mantissa: String = "0"
48-
var inMantissa: Bool = false
49-
var isNegative: Bool = false
50-
let decimalPoint = self._localDecimalPoint()
51-
52-
let charactersEnumerator = self.characters.enumerated()
53-
for (i, c) in charactersEnumerator {
54-
if i == 0 && c == "-" {
55-
isNegative = true
56-
continue
57-
}
58-
59-
if c == decimalPoint {
60-
inMantissa = true
61-
continue
62-
}
63-
64-
if Int(String(c)) != nil {
65-
if !inMantissa {
66-
characteristic.append(c)
67-
} else {
68-
mantissa.append(c)
69-
}
70-
} else {
71-
/* Non-numeric character found, bail */
72-
return nil
73-
}
74-
}
75-
76-
let doubleCharacteristic = Double(Int(characteristic)!)
77-
return (doubleCharacteristic +
78-
Double(Int(mantissa)!) / pow(Double(10), Double(mantissa.characters.count - 1))) *
79-
(isNegative ? -1 : 1)
46+
let decimalPoint = String(self._localDecimalPoint())
47+
guard decimalPoint == "." || self.range(of: ".") == nil else { return nil }
48+
let localeSelf = self.replacingOccurrences(of: decimalPoint, with: ".")
49+
return Double(localeSelf)
8050
}
8151

8252
/**

Tests/CommandLineKitTests/StringExtensionTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,8 @@ class StringExtensionTests: XCTestCase {
7171

7272

7373
/* Various extraneous chars */
74-
let k = "+42.3".toDouble()
75-
XCTAssertNil(k, "Parsed double with extraneous +")
74+
let k = "+42.3".toDouble() // 4 Jan 2017: leading + is valid language syntax
75+
XCTAssertEqual(k, 42.3, "Failed to parse double with leading +")
7676

7777
let l = " 827.2".toDouble()
7878
XCTAssertNil(l, "Parsed double with extraneous space")

0 commit comments

Comments
 (0)