forked from trustwallet/trust-wallet-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecimalFormatter.swift
64 lines (62 loc) · 2.45 KB
/
DecimalFormatter.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
final class DecimalFormatter {
/// Locale of a `DecimalFormatter`.
var locale: Locale
/// numberFormatter of a `DecimalFormatter` to represent curent locale.
private lazy var numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.locale = self.locale
formatter.numberStyle = .decimal
formatter.isLenient = true
return formatter
}()
/// usFormatter of a `DecimalFormatter` to represent decimal separator ".".
private lazy var usFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.numberStyle = .decimal
formatter.isLenient = true
return formatter
}()
/// frFormatter of a `DecimalFormatter` to represent decimal separator ",".
private lazy var frFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "fr_FR")
formatter.numberStyle = .decimal
formatter.isLenient = true
return formatter
}()
/// enCaFormatter of a `DecimalFormatter` to represent decimal separator "'".
private lazy var enCaFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_CA")
formatter.numberStyle = .decimal
formatter.isLenient = true
return formatter
}()
/// Initializes a `DecimalFormatter` with a `Locale`.
init(locale: Locale = .current) {
self.locale = locale
self.numberFormatter = NumberFormatter()
self.numberFormatter.locale = self.locale
self.numberFormatter.numberStyle = .decimal
self.numberFormatter.isLenient = true
}
/// Converts a String to a `NSumber`.
///
/// - Parameters:
/// - string: string to convert.
/// - Returns: `NSumber` represenation.
func number(from string: String) -> NSNumber? {
return self.numberFormatter.number(from: string) ?? self.usFormatter.number(from: string) ?? self.frFormatter.number(from: string) ?? self.enCaFormatter.number(from: string)
}
/// Converts a NSumber to a `String`.
///
/// - Parameters:
/// - number: nsnumber to convert.
/// - Returns: `NSumber` represenation.
func string(from number: NSNumber) -> String? {
return self.numberFormatter.string(from: number)
}
}