how to convert float to decimal in swift

huangapple go评论95阅读模式
英文:

how to convert float to decimal in swift

问题

在Swift中,您可以如何将浮点值转换为十进制值,然后再添加两个变量?我遇到了一个错误:error: no exact matches in call to initializer。以下是代码示例:

  1. let decimalValue: Decimal = 2.0
  2. let floatValue: Float = 12.00
  3. let sum = Decimal(floatValue) + decimalValue /// error: no exact matches in call to initializer
  4. print(sum)

请注意,这段代码中的错误是由于Decimal的初始化方法没有与Float类型的参数匹配。要解决这个问题,您可以使用NSDecimalNumber类来进行转换和计算。以下是修改后的代码示例:

  1. let decimalValue: Decimal = 2.0
  2. let floatValue: Float = 12.00
  3. let decimalNumber = NSDecimalNumber(value: floatValue)
  4. let sum = decimalNumber.decimalValue + decimalValue
  5. print(sum)

这样,您就可以将Float值转换为Decimal值,并成功进行加法运算。

英文:

In swift, how can I convert float value to decimal value and then add 2 variable? I have
error: no exact matches in call to initializer

  1. let decimalValue: Decimal = 2.0
  2. let floatValue: Float = 12.00
  3. let sum = Decimal(floatValue) + decimalValue /// error: no exact matches in call to initializer
  4. print(sum)

答案1

得分: 4

文档显示没有接受Float类型的初始化器。只有init(_ value: Double)init(floatLiteral value: Double)两个选项。

你有两个合理的选择:

  1. floatValue隐式声明为Double

    1. let decimalValue: Decimal = 2.0
    2. let floatValue = 12.00 // <- 推断为Double类型
    3. let sum = Decimal(floatValue) + decimalValue
  2. 调用init(_ value: Double)

    1. let decimalValue: Decimal = 2.0
    2. let floatValue : Float = 12.00
    3. let sum = Decimal(Double(floatValue)) + decimalValue
英文:

The documentation reveals that there is no initializer which accepts a Float. There are only init(_ value: Double) and init(floatLiteral value: Double)

You have two reasonable options:

  1. Declare floatValue implicit as Double

    1. let decimalValue: Decimal = 2.0
    2. let floatValue = 12.00 // &lt;- inferred as Double
    3. let sum = Decimal(floatValue) + decimalValue
  2. Call init(_ value: Double)

    1. let decimalValue: Decimal = 2.0
    2. let floatValue : Float = 12.00
    3. let sum = Decimal(Double(floatValue)) + decimalValue

huangapple
  • 本文由 发表于 2023年8月8日 21:28:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定