skip to Main Content

I am getting some coordinates from server in string array. And I am trying to save those coordinates in SQLite Database by splitting and converting them to double value. But some coordinates are getting saved in scientific notations. For example I am getting the following coordinate from server:
"-0.0000558,51.3368066"
I am splitting the string and converting it to double resulting in the following values:
[-5.58e-05,51.3368066]
I have tried following solutions but still returning same result:

1.

Double(latLongArr[0])
extension String{
  var doubleValue: Double? {
    return NumberFormatter().number(from: self)?.doubleValue
  }
}
extension String{
  var doubleValue: Double? {
    let numberFormatter = NumberFormatter()
     numberFormatter.allowsFloats = true
     numberFormatter.maximumFractionDigits = 10
     numberFormatter.numberStyle = .decimal
     return numberFormatter.number(from: "(self)")!.doubleValue
  }
}

I have used the above code but it still returns in scientific format but I need it in normal decimal format. So what is the issue?

3

Answers


  1. The last option is the option I would go for and I believe it works right.

    I believe your issue is only when you print to console:

    Double Decimal Precision Scientific Notation Swift iOS

    As you can see, the double variable is actually converted properly but just when it is formatted to print to the console it shows it as a scientific notation string.

    Your other option besides using doubleValue is to use decimalValue

    I suggest putting a breakpoint and checking the actual value of your double than reviewing it from the console output which is a formatted string.

    Just for reference, code used in the image above:

    let number = "-0.0000558"
    
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .decimal
    numberFormatter.maximumFractionDigits = 10
    let finalNumber = numberFormatter.number(from: number)
    
    let decimalNumber = finalNumber!.decimalValue
    let doubleNumber = finalNumber!.doubleValue
    
    print(decimalNumber)
    print(doubleNumber)
    
    Login or Signup to reply.
  2. I have used the below extension to represent scientific values in the decimal format.

    extension String {
        
        func getDecimalValue() -> Decimal{
            return NSNumber(value: Double(self)!).decimalValue
        }
    }
    

    Usage:

    let numberString = "+5.58e-05"
    print(numberString.getDecimalValue())  //0.0000558
    
    Login or Signup to reply.
  3. If you want to print your Doubles without scientific notation use
    String(format: "%.7f", value).

    Example:

    let value = Double(3.141592)
    print(String(format: "%.7", value)
    

    will print 3.1415920.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search