Only show decimal portion of Double with the decimal point

天涯浪子 提交于 2020-01-02 22:07:41

问题


I'm trying to only show the decimal portion of a number but it keeps printing the number with the decimal point:

for number 223.50:

changeAmountLabel.text = "\(balance.truncatingRemainder(dividingBy: 1))"

this will print .5, but what needs to be printed is 50, is there a way to do this?


回答1:


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
    }
}



回答2:


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"


来源:https://stackoverflow.com/questions/46412645/only-show-decimal-portion-of-double-with-the-decimal-point

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!