Only show decimal portion of Double with the decimal point

岁酱吖の 提交于 2019-12-08 09:01:27

You can do this by using a NumberFormatter.

Try this:

let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 3


let number = 223.50
if let str = formatter.string(from: NSNumber(value: number)) as? String {
    if let range = str.range(of: ".") {
        let value = str.substring(from: range.upperBound)
        print(value) // 50
    }
}

Update for Swift 4:

if let str = formatter.string(for: number) {
    if let range = str.range(of: ".") {
        let value = str[range.upperBound...]
        print(value) // 50
    }
}

You just need to floor your balance and subtract the result from it, next multiply it by 100. After that you can format the result as needed:

let balance =  223.50
let cents = (balance - floor(balance)) * 100
let formatted = String(format: "%.0f", cents)  // "50"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!