Convert high numbers to lower format [duplicate] - ios

This question already has answers here:
NSNumberFormatter : Show 'k' instead of ',000' in large numbers?
(3 answers)
How to get file size properly and convert it to MB, GB in Cocoa? [duplicate]
(3 answers)
Closed 6 years ago.
How can I change high numbers to something like:
1,000 = 1K
1,250 = 1,2K
10,200 = 10,2K
102,000 = 102K
1,200,000 = 1,2M
Or something like that?
This is how I set the number:
textCell?.ll1.text = "\(String(thumb[indexPath.row].count))"
textCell?.ll2.text = "\(String(love[indexPath.row].count))"

let formatter = NSByteCountFormatter()
That's it ;)
Examples:
let oneFormattedNumber = formatter.stringFromByteCount(1025000000000)
let formattedList = [1_000, 1_250, 10_200, 102_000, 1_200_000].map(formatter.stringFromByteCount)

You can add this functionality as an extension to Int:
extension Int {
func shortLiteralDescription() -> String {
var factor = 0
let tokens = ["","K", "M", "G","T","P"] //If you think you will need to express more, add them here
var value = Double(self);
while (value > 1000) {
value /= 1000
factor++
}
return "\(value)\(tokens[factor])"
}
}
And then:
400200.shortLiteralDescription() //400.2K
4000.shortLiteralDescription() //4.0K

Related

Can't get correct number formatting as a string [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 2 years ago.
I've developed a custom control for money input, which contains UITextField and UILabel. When the user taps on it, it becomes active and switches to the UITextField for data input and accepts only numbers and dot symbol, when the user finishes editing it becomes passive and switches to UILabel just to show formatted money value. But there is one little issue which I'm unable to fix a lot of days already.
Let's say the user writes down 88.99 and presses done, this becomes "$ 88.99" in a UILabel, next when the user again taps on it to edit the initial value I get the following value "88.98999999999999". To not present the entire code I selected the core part in a playground format which gives the same result as in my complete project:
extension NumberFormatter {
static public func defaultCurrencyFormatter() -> NumberFormatter {
let formatter = NumberFormatter()
formatter.usesGroupingSeparator = true
formatter.numberStyle = .currency
formatter.currencySymbol = ""
formatter.minimumFractionDigits = 1
formatter.maximumFractionDigits = 2
formatter.currencyGroupingSeparator = ","
formatter.currencyDecimalSeparator = "."
return formatter
}
}
let stringValue = NumberFormatter.defaultCurrencyFormatter().number(from: "88.99")?.stringValue
print(stringValue) // result is Optional("88.98999999999999")
I have no idea why using this NumberFormatter I get such a result. I was thinking that explicitly setting minimumFractionDigits and maximumFractionDigits will solve my issue but it does not affect my result
NumberFormatter is legacy from objc and it operates with NSNumber/CGFloat etc. and usually it is helpful for localized text formatting. Much powerful and convenient parser for numbers is Scanner but if you don't have complex data structure to parse and don't want to deal with Floating-point error mitigation just use swift's Float:
// Float from string
if let float = Float("88.99") {
print(float)
// String from float
let text = String(float)
print(text)
}
Prints:
88.99
88.99
Try this:
extension String {
var currencyStyle: String? {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 1
formatter.maximumFractionDigits = 2
formatter.usesGroupingSeparator = true
formatter.groupingSize = 3
formatter.currencyGroupingSeparator = ","
formatter.currencyDecimalSeparator = "."
if let double = Double(self) {
let number = NSNumber(value: double)
return formatter.string(from: number)
}
return nil
}
}
to use it:
let str = "12388.98999999999999".currencyStyle
print(str) // Optional("12,388.99")

Assign values of an Int to two separate variables [duplicate]

This question already has answers here:
How to split an Int to its individual digits?
(11 answers)
Closed 3 years ago.
say for example i have an Int var firstInt = 23 what i need is i want to assign the value of firstInt to two separate variables so the output would be var x = 2 and var y = 3. i tried converting the firstInt to a string like so var strFirstInt = String(firstInt) and wanted to assign the first index of the string to a different variable and the second index to another variable and convert them to Int but i couldn't pick the string by index. so any ideas how to do this?
You can use .compactMap from String like this :
let numberInt = 23
let digits = String(numberInt).compactMap{ $0.wholeNumberValue}
Response :
[2, 3]
And with this array, you put the first member to the first var and seconds to another:
var x = digits[0]
var y = digits[1]
print("The decade is \(x) and units is \(y)")
Response:
The decade is 2 and units is 3
Convert the firstInt to String and then to Array,
var firstInt = 23
let arr = Array(String(firstInt)).map({ String($0 )})
Next, get the elements as per the index from array, i.e.
var x = Int(arr[0])
var y = Int(arr[1])

How to convert Array of Months Name to Months Number in swift [duplicate]

This question already has answers here:
How to find index of list item in Swift?
(23 answers)
Closed 4 years ago.
In my project, I am selecting months from picker view that month name is placed in Text field. But I have to send Month Number to the server.
This is my month array
var monthsArray = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
Here I am getting a problem. For an example If I select April, I have to send 4 to the server, How to do this task please someone help/ advise me.
If you have the text value, just find the index of that value in the array and then add 1 (because the array is zero index based)
Something like this should work:
var monthsArray = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
if let index = monthsArray.index(of: "APRIL") { // index will be 3 (zero based)
let monthNumber = index + 1 // +1 as explained earlier
print(monthNumber) // output: 4
}
A function like this may help
func getMonthIndex(_ month: String) -> Int {
let months = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
var monthIndex = -1
if let idx = months.index(of: month.uppercased()) {
monthIndex = idx + 1
}
return monthIndex
}
which can be used as follows :
var idx = getMonthIndex("January") //1
idx = getMonthIndex("JANUARY") //1
idx = getMonthIndex("DECEMBER") //12
idx = getMonthIndex("DECEMBERRRR") //-1
In the snipped above "month.uppercased()" is very important this will help to identify months in all cases such as "January", "JANUARY" OR "january"

Get currency code / symbol from language code in iOS [duplicate]

This question already has answers here:
Get local currency in swift
(2 answers)
iPhone: How to get local currency symbol (i.e. "$" instead of "AU$")
(7 answers)
Closed 5 years ago.
In my swift project, I have to show the list of available Locale Identifiers. If user selects a locale like "ar" i.e. lanugage code alone. How I can get the currency symbols or number formats for this.
func listCountriesAndCurrencies() {
let localeIds = Locale.availableIdentifiers
var countryCurrency = [String: String]()
for localeId in localeIds {
let locale = Locale(identifier: localeId)
if let country = locale.regionCode, country.count == 2 { // how to get currency for locale without region code ?
if let currency = locale.currencySymbol {
countryCurrency[localeId] = currency
}
}
}
let sorted = countryCurrency.keys.sorted()
for country in sorted {
let currency = countryCurrency[country]!
print("country: \(country), currency: \(currency)")
}
}
My question is explained in the code comment

How to get substring of String in Swift? [duplicate]

This question already has answers here:
How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
(33 answers)
Closed 7 years ago.
If I want to get a value from the NSString "😃hello World😃", what should I use?
The return value I want is "hello World".
The smileys can be any string. so i need some regexp to this.
There's more than one way to do it.
First: String in Swift 1.2 is bridged to NSString properly so the answer could be : How to get substring of NSString?
Second: This answer will deal with emoticon characters too.
var s = "😃hello World😃"
let index = advance(s.startIndex, 1) // index is a String.Index to the 2nd glyph, “h”
let endIndex = advance(s.startIndex, 12)
let substring=s[index..<endIndex] // here you got "hello World"
if let emojiRange = s[index...s.endIndex].rangeOfString("😃") {
let substring2 = s[index..<emojiRange.startIndex] // here you get "hello World"
}

Resources