This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 441
/
NumberExtensions.swift
55 lines (43 loc) · 1.66 KB
/
NumberExtensions.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
// MARK: - INT
public extension Int {
/// Returns larger numbers in K(thousands) and M(millions) friendly format.
/// Example : 123 456 -> 123K, 3000 -> 3k, 3400 -> 3.4K
var kFormattedNumber: String {
if self >= 1000 && self < 10000 {
return String(format: "%.1fK", Double(self / 100) / 10).replacingOccurrences(of: ".0", with: "")
}
if self >= 10000 && self < 1000000 {
return "\(self/1000)K"
}
if self >= 1000000 && self < 10000000 {
return String(format: "%.1fM", Double(self / 100000) / 10).replacingOccurrences(of: ".0", with: "")
}
if self >= 10000000 {
return "\(self/1000000)M"
}
return String(self)
}
}
public extension NSDecimalNumber {
/// Returns a currency formatted string where the currency's symbol is in front.
/// For example $19.99.
func frontSymbolCurrencyFormatted(with locale: Locale) -> String? {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = locale
// Hide currency symbol, we append it manually in front of the String.
formatter.currencySymbol = ""
formatter.currencyCode = ""
let currencySymbol = locale.currencySymbol ?? ""
// Making currency codes empty adds extra space at the end, trimming it here.
guard
let formatted = formatter.string(from: self)?
.trimmingCharacters(in: .whitespacesAndNewlines)
else { return nil }
return currencySymbol + formatted
}
}