我是 Swift 新手。
struct Money{
var amount: Decimal = 0
}
var myMoney = Money()
myMoney.amount = 10.019999999999997952
如果我在
myMoney.amount
上搜索值:10.01,它应该返回 true。我只关心小数点后2位。
我尝试使用范围修改器但没有成功。
如果您只想查看十进制值的字符串表示形式是否以“10.01”等字符串开头...
struct Money{
var amount: Decimal = 0
func beginsWith(_ str: String) -> Bool {
return ("\(amount)").hasPrefix(str)
}
}
然后:
var myMoney = Money()
myMoney.amount = 10.019999999999997952
var searchFor: String = "10.01"
if myMoney.beginsWith(searchFor) {
print("yes, it begins with:", searchFor)
} else {
print("no, it doesn't begin with:", searchFor)
}
searchFor = "1001"
if myMoney.beginsWith(searchFor) {
print("yes, it begins with:", searchFor)
} else {
print("no, it doesn't begin with:", searchFor)
}
searchFor = "10.02"
if myMoney.beginsWith(searchFor) {
print("yes, it begins with:", searchFor)
} else {
print("no, it doesn't begin with:", searchFor)
}
调试控制台输出:
yes, it begins with: 10.01
no, it doesn't begin with: 1001
no, it doesn't begin with: 10.02
通常在处理
Decimal
类型时,我们可能会考虑对 amount
中存储的值进行四舍五入:
struct Money{
var amount: Decimal = 0
}
var myMoney = Money()
var value: Decimal = 10.019999999999997952
NSDecimalRound(&myMoney.amount, &value, 2, .down) // or `.plain`
print(myMoney.amount)
或者,如果您经常这样做,您可以定义一个扩展来为您执行此操作:
extension Double {
func decimalRounded(to scale: Int = 2, roundingMode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
var newValue: Decimal = 0
var currentValue = Decimal(self)
NSDecimalRound(&newValue, ¤tValue, scale, roundingMode)
return newValue
}
}
然后:
var myMoney = Money()
myMoney.amount = 10.019999999999997952.decimalRounded(roundingMode: .down)
print(myMoney.amount)