Skip to content

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

@doozMen

Description

@doozMen

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 .

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions