Is there any way to increase the number limit of double type in Swift?

207 views Asked by At

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, +)
2

There are 2 answers

0
Josh Homann On BEST ANSWER

Are you trying to sum up the first element of each array (which is a string?). If so this Playground shows how:

import UIKit

let records: [[String]] = [(100..<103).map{"\($0)"},
                           (200..<203).map{"\($0)"},
                           (300..<303).map{"\($0)"}]
print(records)
let sum = records.flatMap {$0.first}.flatMap{Double($0)}.reduce(0, +)
print(sum)

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.

3
vadian On

Actually both dropFirst() and reduce(_:_) are supposed to work with this syntax. Is the code in the question the real code?

This works in a Playground

let array = ["\n1.2", "\n3.5", "\n6.7"]
let incomeSum = array.map{Double($0.dropFirst()) ?? 0.00}.reduce(0, +)
print(incomeSum) // 11.4
  • To fix the Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String' error create a new string from the result (e.g. String($0.amount!.dropFirst()))

  • I don't understand the second error – which indicates a type mismatch – since literal 0 is treated both as Int and Double