I have an array of values like [0.75, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.004000000000
You can use NumberFormatter to fix the minimum and maximum fraction digits and use a set to filter the duplicate elements:
let array = [0.75, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0040000000000000001]
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.minimumFractionDigits = 3
numberFormatter.maximumFractionDigits = 3
var set = Set()
let orderedSet: [Double] = array.flatMap {
guard let string = numberFormatter.string(for: $0) else { return nil }
return set.insert(string).inserted ? $0 : nil
}
orderedSet // [0.75, 0.005, 0.004]
If you need Strings (as suggested by @Hamish):
var set = Set()
let orderedSet: [String] = array.flatMap {
guard let string = numberFormatter.string(for: $0) else { return nil }
return set.insert(string).inserted ? string : nil
}
orderedSet // ["0.750", "0.005", "0.004"]