Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

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

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, +)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...