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 | |
) | |
} | |
} | |
7 видов NumberFormatter.RoundingMode:
Пример для понимания:
import Foundation
let numberFormatter = NumberFormatter()
let number = -1.45
let number2 = 1.45
numberFormatter.maximumFractionDigits = 1
// Округляем от нуля
numberFormatter.roundingMode = .up
print("up")
print(numberFormatter.string(for: number)) // -1.5
print(numberFormatter.string(for: number2)) // 1.5
// Округляем в сторону нуля
numberFormatter.roundingMode = .down
print("\ndown")
print(numberFormatter.string(for: number)) // -1.4
print(numberFormatter.string(for: number2)) // 1.4
// Округление в сторону положительной бесконечности
numberFormatter.roundingMode = .ceiling
print("\nceiling")
print(numberFormatter.string(for: number)) // -1.4
print(numberFormatter.string(for: number2)) // 1.5
// Округляем в сторону минус бесконечности
numberFormatter.roundingMode = .floor
print("\nfloor")
print(numberFormatter.string(for: number)) // -1.5
print(numberFormatter.string(for: number2)) // 1.4
// Округлите в сторону ближайшего целого числа или если оно равноудалено, то от нуля
numberFormatter.roundingMode = .halfUp
print("\nhalfUp")
print(numberFormatter.string(for: number)) // -1.5
print(numberFormatter.string(for: number2)) // 1.5
// Округлите в сторону ближайшего целого числа или если оно равноудалено, то к нулю
numberFormatter.roundingMode = .halfDown
print("\nhalfDown")
print(numberFormatter.string(for: number)) // -1.4
print(numberFormatter.string(for: number2)) // 1.4
// Округлите в сторону ближайшего целого числа или если оно равноудалено, то в сторону четного числа
numberFormatter.roundingMode = .halfEven
print("\nhalfEven")
print(numberFormatter.string(for: number)) // -1.4
print(numberFormatter.string(for: number2)) // 1.4
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: