Last active
October 7, 2024 19:01
-
-
Save eldaroid/af2bddcb4f5d658211fcfc4b2ae4242f to your computer and use it in GitHub Desktop.
RU: Преобразование чисел в удобочитаемый формат, добавляя соответствующие постфиксы для больших чисел (например, 123 тысяч, 5 миллионов, 8 миллиардов и т.д.). EN: Convert numbers into a readable format by adding appropriate postfixes for large numbers (e.g. 123 thousand, 5 million, 8 billion, etc.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension Double { | |
func humanFormatted( | |
groupingSeparator: String = " ", | |
roundingMode: NumberFormatter.RoundingMode = .halfEven, | |
fractionDigits: Int = 1, | |
threshold: Double = 9_999 | |
) -> (stringValue: String, postfix: String?) { | |
let dividerNames: [String?] = [nil, "тыс.", "млн", "млрд", "трлн", "квадрлн"] | |
var index = 0 | |
var humanValue = self | |
while abs(humanValue) > threshold { | |
humanValue /= 1_000 | |
index += 1 | |
} | |
let formatter = NumberFormatter() | |
let number = NSNumber(value: humanValue) | |
formatter.roundingMode = roundingMode | |
formatter.minimumFractionDigits = 0 | |
formatter.maximumFractionDigits = fractionDigits | |
formatter.groupingSeparator = groupingSeparator | |
formatter.numberStyle = .decimal | |
let stringValue = formatter.string(from: number)?.replacingOccurrences(of: ".", with: ",") ?? "" | |
return ( | |
stringValue: stringValue, | |
postfix: index < dividerNames.count ? dividerNames[index] : nil | |
) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
7 видов NumberFormatter.RoundingMode:
Пример для понимания: