如何在swift3中的十进制字符串末尾添加一个零

时间:2017-09-11 10:24:22

标签: swift3 nsnumberformatter

我从网络服务获得一个特定的双号,如网络服务中的0.097或0.034。因此,如果我得到一个特定的数字,如0.56或0.5,我需要在0.56中加零,在0.5中加两个零。如何在swift3中执行此操作? 目前我在做:

    class func appendString(data: Int) -> String {
    let value = data
    let formatter = NumberFormatter()
    formatter.minimumFractionDigits = 3 // for float
    formatter.maximumFractionDigits = 3 // for float
    formatter.minimumIntegerDigits = 1
    formatter.paddingPosition = .afterPrefix
    formatter.paddingCharacter = "0"
    return formatter.string(from: NSNumber(floatLiteral: Double(value)))!
  }

任何想法如何实现上述逻辑?

2 个答案:

答案 0 :(得分:6)

您在Int类型中传递数据输入的问题,因此它将始终忽略分数

见下一个例子[Swift 3.1]

func formatNumber(_ number: Double) -> String? {

   let formatter = NumberFormatter()
   formatter.minimumFractionDigits = 3 // minimum number of fraction digits on right
   formatter.maximumFractionDigits = 3 // maximum number of fraction digits on right, or comment for all available
   formatter.minimumIntegerDigits = 1 // minimum number of integer digits on left (necessary so that 0.5 don't return .500)

   let formattedNumber = formatter.string(from: NSNumber.init(value: number))

   return formattedNumber

}

let formattedNumber = formatNumber(0.5)
print(formattedNumber) // Optional("0.500")

答案 1 :(得分:0)

对您的代码进行一些小改动:

func appendString(data: Double) -> String { // changed input type of data
    let value = data
    let formatter = NumberFormatter()
    formatter.minimumFractionDigits = 3 // for float
    formatter.maximumFractionDigits = 3 // for float
    formatter.minimumIntegerDigits = 1
    formatter.paddingPosition = .afterPrefix
    formatter.paddingCharacter = "0"
    return formatter.string(from: NSNumber(floatLiteral: value))! // here double() is not required as data is already double
}

print(appendString(data: 0.5)) // 0.500