Search code examples
swiftstringdouble

String value converted to double automatically change to decimal value in Swift


Working with Swift. I am converting value from String to double.

let value: String = "8"    
var size: Double   
size = Double(value) 
size = 8.0 // 8.0

Result should be 8 unless string value is 8.0


Solution

  • Double only stores a numeric magnitude. "8" and "8.0" have the same magnitude, so they get represented by the same Double value. Whether you show trailing 0s or not is a consequence of how you choose to format and present your values.

    print does it one way for debugging, but NumberFormatter gives you more control to format numbers for real, non-debugging purposes.