问题
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