我试图用以下代码将Decimal转换为Int:
Int(pow(Decimal(size), 2) - 1)
但我得到了:
.swift:254:43: Cannot invoke initializer for type 'Int' with an argument list of type '(Decimal)'
这里我知道pow正在返回一个Decimal
,但Int似乎没有构造函数和成员函数来将Decimal
转换为Int
如何在Swift 3中将Decimal转换为Int?
这是我最新的答案(感谢Martin R和OP的评论(。OP的问题只是在结果中减去1之后将pow(x: Decimal,y: Int) -> Decimal
函数强制转换为Int。我已经在NSDecimal的SO帖子和苹果关于Decimal文档的帮助下回答了这个问题。您必须将结果转换为NSDecimalNumber,然后再将其转换为Int:
let size = Decimal(2)
let test = pow(size, 2) - 1
let result = NSDecimalNumber(decimal: test)
print(Int(result)) // testing the cast to Int
let decimalToInt = (yourDecimal as NSDecimalNumber).intValue
或者正如@MartinR所建议的:
let decimalToInt = NSDecimalNumber(decimal: yourDecimal).intValue
如果你有一个很长的小数,那么要小心四舍五入错误
let decimal = Decimal(floatLiteral: 100.123456)
let intValue = (decimal as NSDecimalNumber).intValue // This is 100
然而
let veryLargeDecimal = Decimal(floatLiteral: 100.123456789123)
let intValue = (veryLargeDecimal as NSDecimalNumber).intValue // This is -84 !
我确保在使用NSDecimalRound
(可以放在Decimal的扩展中(将Decimal转换为Int之前,我对其进行了四舍五入。
var veryLargeDecimal = Decimal(floatLiteral: 100.123456789123)
var rounded = Decimal()
NSDecimalRound(&rounded, &veryLargeDecimal, 0, .down)
let intValue = (rounded as NSDecimalNumber).intValue // This is now 100
发布的两个答案都没有错,但我想提供一个扩展,以减少需要经常使用它的场景的冗长性。
extension Decimal {
var int: Int {
return NSDecimalNumber(decimal: self).intValue
}
}
称之为:
let powerDecimal = pow(2, 2) // Output is Decimal
let powerInt = powerDecimal.int // Output is now an Int
不幸的是,使用所提供的一些方法会出现间歇性故障。
NSDecimalNumber(decimal: <num>).intValue
会产生意想不到的结果。。。
(lldb) po NSDecimalNumber(decimal: self)
10.6666666666666666666666666666666666666
(lldb) po NSDecimalNumber(decimal: self).intValue
0
我认为这里还有更多的讨论,@Martin在这里指出了
我没有直接使用十进制值,而是在将decimal转换为Int.之前,先将其转换为整数
extension Decimal {
func rounded(_ roundingMode: NSDecimalNumber.RoundingMode = .down, scale: Int = 0) -> Self {
var result = Self()
var number = self
NSDecimalRound(&result, &number, scale, roundingMode)
return result
}
var whole: Self { rounded( self < 0 ? .up : .down) }
var fraction: Self { self - whole }
var int: Int {
NSDecimalNumber(decimal: whole).intValue
}
}
只需使用Decimal
的描述,String
替换NSDecimalNumber
来桥接它。
extension Decimal {
var intVal: Int? {
return Int(self.description)
}
}