programing tip

Swift double to string

itbloger 2020. 8. 26. 07:40
반응형

Swift double to string


xCode 6을 업데이트하기 전에 double을 string bur로 캐스팅하는 데 문제가 없었습니다. 이제 오류가 발생했습니다.

var a: Double = 1.5
var b: String = String(a)

"double is not convertible to string"이라는 오류 메시지가 표시됩니다. 다른 방법이 있습니까?


캐스팅이 아니라 형식이있는 값에서 문자열을 생성합니다.

let a:Double = 1.5
let b:String = String(format:"%f", a)
print("b: \(b)") // b: 1.500000

다른 형식 :

let c:String = String(format:"%.1f", a)
print("c: \(c)") // c: 1.5

let myDouble = 1.5 
let myString = myDouble.description

Xcode 7.1 업데이트 • Swift 2.1 :

이제 Double도 String으로 변환 할 수 있으므로 원하는대로 간단히 사용할 수 있습니다.

let myDouble = 1.5
let myDoubleString = String(myDouble)   // "1.5"

Xcode 8.3.2 • Swift 3.1 :

Swift 3 이상 에서는 확장 LosslessStringConvertible하여 일반화 할 수 있습니다.

extension LosslessStringConvertible { 
    var string: String { return .init(self) } 
}

1.0.string  //  "1.0"

고정 된 소수 자릿수의 경우 Double을 확장 할 수도 있습니다.

extension FloatingPoint {
    func fixedFraction(digits: Int) -> String {
        return String(format: "%.\(digits)f", self as! CVarArg)
    }
}

숫자 형식 (최소 및 최대 분수 자릿수 및 반올림 모드)에 대한 추가 제어가 필요한 경우 NumberFormatter를 사용할 수 있습니다.

extension Formatter {
    static let number = NumberFormatter()
}

extension FloatingPoint {
    func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
        Formatter.number.minimumFractionDigits = min
        Formatter.number.maximumFractionDigits = max
        Formatter.number.roundingMode = roundingMode
        Formatter.number.numberStyle = .decimal
        return Formatter.number.string(for: self) ?? ""
    }
}

2.12345.fractionDigits()                                    // "2.12"
2.12345.fractionDigits(min: 3, max: 3, roundingMode: .up)   // "2.124"

@Zaph 답변 외에도 다음을 만들 수 있습니다. extension:

extension Double {
    func toString() -> String {
        return String(format: "%.1f",self)
    }
}

용법:

var a:Double = 1.5
println("output: \(a.toString())")  // output: 1.5

Swift 3+: Try these line of code

let num: Double = 1.5

let str = String(format: "%.2f", num)

to make anything a string in swift except maybe enum values simply do what you do in the println() method

for example:

var stringOfDBL = "\(myDouble)"

Swift 4: Use following code

let number = 2.4
let string = String(format: "%.2f", number)

This function will let you specify the number of decimal places to show:

func doubleToString(number:Double, numberOfDecimalPlaces:Int) -> String {
    return String(format:"%."+numberOfDecimalPlaces.description+"f", number)
}

Usage:

let numberString = doubleToStringDecimalPlacesWithDouble(number: x, numberOfDecimalPlaces: 2)

In swift 3:

var a: Double = 1.5
var b: String = String(a)

In swift 3 it is simple as given below

let stringDouble =  String(describing: double)

I would prefer NSNumber and NumberFormatter approach (where need), also u can use extension to avoid bloating code

extension Double {

   var toString: String {
      return NSNumber(value: self).stringValue
   }

}

U can also need reverse approach

extension String {

    var toDouble: Double {
        return Double(self) ?? .nan
    }

}

var b = String(stringInterpolationSegment: a)

This works for me. You may have a try


In Swift 4 if you like to modify and use a Double in the UI as a textLabel "String" you can add this in the end of your file:

    extension Double {
func roundToInt() -> Int{
    return Int(Darwin.round(self))
}

}

And use it like this if you like to have it in a textlabel:

currentTemp.text = "\(weatherData.tempCelsius.roundToInt())"

Or print it as an Int:

print(weatherData.tempCelsius.roundToInt())

Swift 5: Use following code

extension Double {

    func getStringValue(withFloatingPoints points: Int = 0) -> String {
        let valDouble = modf(self)
        let fractionalVal = (valDouble.1)
        if fractionalVal > 0 {
            return String(format: "%.\(points)f", self)
        }
        return String(format: "%.0f", self)
    }
}

참고URL : https://stackoverflow.com/questions/25339936/swift-double-to-string

반응형