I'm try to filter my array and sum the amount. It works but when the number is above 999.99, it will getting nil. Is there any way to increase the number limit of double type? Is it possible?
largest number: 100,000,000.00
incomeFilter = record.filter { $0.recordtype!.contains("收入") && $0.createdAt! == recordItem.createdAt!}
let incomeSum = incomeFilter.map{Double($0.amount!.dropFirst()) ?? 0.00}.reduce(0, +)
//[9.99, nil]
Other than that, I'm also trying to convert it to Number.
But I found that I can't use the .dropFirst()
function. I got this error Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
after I delete it, It show another error Cannot invoke 'reduce' with an argument list of type '(Int, _)'
How to fix it?
let fmt = NumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let incomeSum = incomeFilter.map{fmt.number(from: $0.amount!) ?? 0.00}.reduce(0, +)
Are you trying to sum up the first element of each array (which is a string?). If so this Playground shows how:
The first flat map makes an array of strings containing the first element from all of the arrays, if a first element exists.
The second flat map converts the strings to double if they can be converted.
The reduce then adds everything up.