【问题标题】:How to properly handle comparison between double values in Swift?如何正确处理 Swift 中双精度值之间的比较?
【发布时间】:2017-11-10 13:13:34
【问题描述】:

我知道有人问过类似的问题,但我仍然无法找到解决方案。

我得到这样的双重价值。

let priceUsdInt = (price as NSString).doubleValue

我想将此值与 1.00 进行比较:

if priceUsdInt > 1.00 {
    let priceUsdCur = priceUsdInt.currencyUS
    finalPriceUsdCur = priceUsdCur
} else {
    let priceUsdCur = priceUsdInt.currencyUS6
    finalPriceUsdCur = priceUsdCur
}

这总是带来两位小数的结果。即使价值远低于 1.00。

基本上,我想要实现的是,如果值小于 1.00,则在转换为货币格式时将其显示到小数点后六位,即 0.123456,如果不是在其后仅显示两位小数,即 1.23。

感谢您的宝贵时间。

【问题讨论】:

  • 不要使用 Double 作为货币。你应该使用十进制
  • 我以前从未使用过十进制。您可以使用 Decimal 而不是 Double 来替换下面的答案吗?
  • 就像我说的那样使用string(for: Any)。您可以传递任何数字类型
  • stackoverflow.com/questions/24960621/… 更新到 Swift 4。现在它也扩展了 Decimal

标签: swift compare double


【解决方案1】:

这演示了当从string 转换为double 值的值低于1.02 位 精度时,货币格式显示6 位 精度以上1.0

let belowOne = ".12023456"

let belowDoubleVal = Double(belowOne) ?? 0.0

let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency

if belowDoubleVal < 1.0 {
    // this handles the 6 digit precision you require when value is below 1.0
    currencyFormatter.minimumFractionDigits = 6
}


// old way using NSSNumber
// let belowOneString = currencyFormatter.string(from: NSNumber(value: belowDoubleVal))

// you can pass the double value to formatter using .string(for: Any) 
// thanks for pointing this out by Leo Dabus
let belowOneString = currencyFormatter.string(for: belowDoubleVal)

【讨论】:

  • 你可以使用Formatter string(for: Any) 方法直接传递Double
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-01
  • 2015-12-17
  • 2012-12-29
  • 1970-01-01
相关资源
最近更新 更多