nerdsupremacist / Syntax

Write value-driven parsers quickly in Swift with an intuitive SwiftUI-like DSL
https://quickbirdstudios.com/blog/swift-string-parse/
MIT License
147 stars 10 forks source link

Numberformatter uses locale, decimal separator `,` is used which causes fatal error #10

Open doozMen opened 1 year ago

doozMen commented 1 year ago

The code

private let numberFormatter = NumberFormatter()
private let doublePrefixes: Set<String> = Set((0...9).map { "\($0)." } + (0...9).map { "\(-$0)." })

public struct DoubleLiteral: Parser {
    public static let kind: Kind = .doubleLiteral

    public init() { }

    public var body: AnyParser<Double> {
        Leaf {
            RegularExpression("-?\\d+(,\\d+)*\\.\\d+(e((-|\\+)?)\\d+)?\\b").map { match -> Double in
                guard let number = numberFormatter.number(from: String(match.text)) else { fatalError() }
                return number.doubleValue
            }
        }
        .optimize(using: doublePrefixes)
    }
}

can work with small adjustment

private let numberFormatter: NumberFormatter = {
  let formatter = NumberFormatter()
  formatter.decimalSeparator = "."
  return formatter
}()

But instead of using NSNumberFormatter is it not more performant to just use Double(String(match.text))? Added bonus this always works with decimal separator .