ios - NumberFormatter() 不强制小数位

标签 ios swift nsnumberformatter nsdecimalnumber

这是我的代码:

extension NSDecimalNumber {
func getFormattedDecimalString() -> String {
    let numberFormatter            = NumberFormatter()
    numberFormatter.minimumFractionDigits = 2
    numberFormatter.maximumFractionDigits = 2
    numberFormatter.numberStyle    = NumberFormatter.Style.decimal
    if let decimalString = numberFormatter.string(from: self) {
        return decimalString
    } else {
        return ""
    }
}
}

如果我有数字 4.11,它会显示 4.11。如果我有数字 4.1,它会显示 4.1。如果我有数字 4,它会显示 4。我希望它显示 4.11、4.10 和 4.00。我认为这就是minimumFractionDigits 的用途。我还尝试添加行 numberFormatter.alwaysShowsDecimalSeparator = true 但这没有任何作用。

最佳答案

实际上是由我犯下的不相关错误引起的:我有两个 ViewController,但我正在编辑错误的一个。代码不正确的是附加到 View 的代码。

关于ios - NumberFormatter() 不强制小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43492794/

相关文章:

ios - NumberFormatter 参数标签 '(_:)' 不匹配任何可用的重载

iphone - NSBundle pathsForResourcesOfType : working unreliably

ios - 在 Swift 中使用 NSDate 无法正确获取日期

ios - 更新具有特定索引的元组数组

ios - NSUnknownKeyException', 原因 : . .. : this class is not key value coding-compliant for the key X. '

ios - 如何在 SwiftUI 中使用 NumberFormatter?

ios - 无法在 iphone 6 上检测到 ibeacon

屏幕边缘附近的 iOS UIButton 无法正常响应点击

ios - 当我在导航 Controller Swift 3 中使用它时,searchBarTextDidBeginEditing 没有被调用。

ios - 使用NSNumberFormatter格式化小数