Swift 2.0 Format 1000's into a friendly K's

swift format number with commas
swift numberformatter decimal
swift number formatting
swift number formatter
swift currency
numberformatter currency
how to input currency format on a text field (from right to left using swift)
swift percentage formatter

I'm trying to write a function to present thousands and millions into K's and M's For instance:

1000 = 1k
1100 = 1.1k
15000 = 15k
115000 = 115k
1000000 = 1m

Here is where I got so far:

func formatPoints(num: Int) -> String {
    let newNum = String(num / 1000)
    var newNumString = "\(num)"
    if num > 1000 && num < 1000000 {
        newNumString = "\(newNum)k"
    } else if num > 1000000 {
        newNumString = "\(newNum)m"
    }

    return newNumString
}

formatPoints(51100) // THIS RETURNS 51K instead of 51.1K

How do I get this function to work, what am I missing?

func formatPoints(num: Double) ->String{
    let thousandNum = num/1000
    let millionNum = num/1000000
    if num >= 1000 && num < 1000000{
        if(floor(thousandNum) == thousandNum){
            return("\(Int(thousandNum))k")
        }
        return("\(thousandNum.roundToPlaces(1))k")
    }
    if num > 1000000{
        if(floor(millionNum) == millionNum){
            return("\(Int(thousandNum))k")
        }
        return ("\(millionNum.roundToPlaces(1))M")
    }
    else{
        if(floor(num) == num){
            return ("\(Int(num))")
        }
        return ("\(num)")
    }

}

extension Double {
    /// Rounds the double to decimal places value
    func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return round(self * divisor) / divisor
    }
}

The updated code should now not return a .0 if the number is whole. Should now output 1k instead of 1.0k for example. I just checked essentially if double and its floor were the same.

I found the double extension in this question: Rounding a double value to x number of decimal places in swift

ios - Swift 2.0 Format 1000's into a friendly K's, I'm trying to write a function to present thousands and millions into K's and M's For instance: 1000 = 1k 1100 = 1.1k 15000 = 15k 115000 = 115k 1000000 = 1m. Rabobank SWIFT FIN - Format description MT942 December 2019 | Version 2.0 11 4.2 Examples field 61 and 86 In the table below examples of different transaction types are listed to show the differences in field 61 and 86. Transaction type Current situation Situation after change in Q2 2020 ATM - credit :61:191211C1,00NMSCNONREF

The extension below does the following-

  1. Will display number 10456 as 10.5k and 10006 as 10k (will not show the .0 decimals).
  2. Will do the exact above for millions and format it i.e. 10.5M and 10M
  3. Will format thousands upto 9999 in currency format i.e. with a comma like 9,999

    extension Double {
        var kmFormatted: String {
    
            if self >= 10000, self <= 999999 {
                return String(format: "%.1fK", locale: Locale.current,self/1000).replacingOccurrences(of: ".0", with: "")
            }
    
            if self > 999999 {
                return String(format: "%.1fM", locale: Locale.current,self/1000000).replacingOccurrences(of: ".0", with: "")
            }
    
            return String(format: "%.0f", locale: Locale.current,self)
        }
    }
    

Usage:

let num: Double = 1000001.00 //this should be a Double since the extension is on Double
let millionStr = num.kmFormatted
print(millionStr)

Prints 1M

And here it is in action-

Swift 2.0 Format 1000's into a friendly K's - ios, I'm trying to write a function to present thousands and millions into K's and M's For instance: 1000 = 1k 1100 = 1.1k 15000 = 15k 115000 = 115k 1000000 = 1m  Rabobank SWIFT FIN - Format description MT940 December 2019 | Version 2.0 12 4.2 Examples field 61 and 86 In the table below examples of different transaction types are listed to show the differences in field 61 and 86. Transaction type Current situation Situation after change in Q2 2020 ATM - credit :61:191211C1,00NMSCNONREF

extension Int {
    var roundedWithAbbreviations: String {
        let number = Double(self)
        let thousand = number / 1000
        let million = number / 1000000
        if million >= 1.0 {
            return "\(round(million*10)/10)M"
        }
        else if thousand >= 1.0 {
            return "\(round(thousand*10)/10)K"
        }
        else {
            return "\(self)"
        }
    }
}

print(11.roundedWithAbbreviations)          // "11"
print(11111.roundedWithAbbreviations)       // "11.1K"
print(11111111.roundedWithAbbreviations)    // "11.1 M"

NumberFormatter, iOS 2.0+; macOS 10.0+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+ Instances of NumberFormatter format the textual representation of cells that contain and thousand separator character ( , ) are converted to appropriately localized  How To Professionally Tint a Car Door window - 2013 VW Jetta (For Beginners ) - Duration: 25:48. Window Tint Warriors Recommended for you

Some Change in Answer(For Int and correct for million):

func formatPoints(num: Int) ->String{
    let thousandNum = num/1000
    let millionNum = num/1000000
    if num >= 1000 && num < 1000000{
        if(thousandNum == thousandNum){
            return("\(thousandNum)k")
        }
        return("\(thousandNum)k")
    }
    if num > 1000000{
        if(millionNum == millionNum){
            return("\(millionNum)M")
        }
        return ("\(millionNum)M")
    }
    else{
        if(num == num){
            return ("\(num)")
        }
        return ("\(num)")
    }

}

Swift: Add separator on Integer using NumberFormatter, Swift: Add separator on Integer using NumberFormatter. Dejan Atanasov. Follow. Jun 15, 2017 · 2 min read. If you want to In this case, it is whitespace but you can add any other special character like dot or comma to make it 1.000 or 1,000. A tutorial for Motic Image Software, microscope camera

For swift 4.0. its work completely fine and answer based on @user3483203

Function for convert Double value to String

func formatPoints(num: Double) ->String{
    var thousandNum = num/1000
    var millionNum = num/1000000
    if num >= 1000 && num < 1000000{
        if(floor(thousandNum) == thousandNum){
            return("\(Int(thousandNum))k")
        }
        return("\(thousandNum.roundToPlaces(places: 1))k")
    }
    if num > 1000000{
        if(floor(millionNum) == millionNum){
            return("\(Int(thousandNum))k")
        }
        return ("\(millionNum.roundToPlaces(places: 1))M")
    }
    else{
        if(floor(num) == num){
            return ("\(Int(num))")
        }
        return ("\(num)")
    }

}

Make one Double extension

extension Double {
    /// Rounds the double to decimal places value
    mutating func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return Darwin.round(self * divisor) / divisor
    }
}

Usage of above function

UILABEL.text = formatPoints(num: Double(310940)!)

Output :

Formatter, Formatting Numbers and Quantities. Class, Example Output, Availability. NumberFormatter, “1,234.56”, iOS 2.0 macOS 10.0+. Swift is a highly available, distributed, eventually consistent object/blob store. Organizations can use Swift to store lots of data efficiently, safely, and cheaply. This documentation is generated by the Sphinx toolkit and lives in the source tree. Additional documentation on Swift and other components of OpenStack can be found on the

Dates, DateComponents and Formatting in Swift – LearnAppMaking, Dates, DateComponents and Formatting in Swift Calculating relative time strings, such as “2 months ago”; Constructing Date objects from date components i.e. it can represent points in time up to 1/1000th of a second. 2017 Suzuki Swift acceleration test with 1.0 BoosterJet engine and 6-speed automatic transmission. 1 on board, A/C off ~1/4 fuel tank dry road.

Double format with Swift, To round a Double with 3 digits precision, first multiply it by 1000, round it and divide Extension for Swift 2 A more general solution is the following extension,​  The group indicated by 0 is a Financial Institution Transfer. Finally, the third digit ( 7) denotes the specific message. In this case, similar to the MT 304, the 7 denotes ‘Notification’. The SWIFT MT 304 and the ISO 15022 MT 307 are equal but were created for different financial groups using different standards.

iOS solution to convert large numbers to smaller format. See : http , iOS solution to convert large numbers to smaller format. See : http://stackoverflow.​com/a/35504720/1661338 - Int+Extenstion.swift. Value : 1000 -> 1K. // Value  2017 Suzuki Swift GLX Turbo 0-100km/h & engine sound. Head over to http://performancedrive.com.au/2017-s for the full review. 2017 Suzuki Swift GLX Turbo 1.0-litre

Comments
  • You're doing integer division which just throws away the remainder. You might want to convert to Doubles to do your math.
  • Use NSByteCountFormatter instead of your own code.
  • I don't do swift, but talking from an Obj-C prospective, I would say that you are using an Int value as input, so num / 1000 is probably not returning any decimals.
  • Have a look at stackoverflow.com/questions/35854069/… (and the linked-to threads).
  • Tried it, but when the number is below 1000 it returns it with .0 so 916 would become 916.0
  • All you would have to do is add one more if statement if the number is less than 1000, and run the same check I ran.
  • I just updated my answer to something that works for numbers under 1000 as well.
  • Code has some bug in swift 4.0.
  • @Rajesh instead of round(self * divisor) / divisor, in Swift 4 do (self * divisor).rounded() / divisor
  • Please fix: your minimum thousand value should be >= 1000 instead of 10000
  • No it should not. This extension will show thousands upto 9999 in a format of 9,999 (with a comma i.e. currency format) example 1000 will be 1,000 ; 2000 will be 2,000. Anything equal to or above 10000 or less than or equal to less than 999999 will show with a 'K' format and so on.
  • Ah I see what you did there. Interesting. Well, for my use case, I ended up changing it to 1000. My apologies for assuming your use case was the same as mine.
  • No Worries, glad you figured it out.
  • I like this answer the best. It was easy to add billion and trillion and passes all my test cases!