Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Numbers in Swift 3

I want to format number to this: 123.234.234.234 from 123234234234 depends on what the user types into the text field. I don't want to manage currency, it's not about currency, it is about the user has to type in a number and this number should be formatted correctly to be easier to read.

Not with a comma, with a dot.

I found only currency stuff in the whole research

like image 954
Glatteisen Avatar asked Jun 19 '17 12:06

Glatteisen


People also ask

How do I change the number format in Swift?

All that we have to do is to set its numberStyle to currency and give it the code of the currency that we're using — like this: extension Price: CustomStringConvertible { var description: String { let formatter = NumberFormatter() formatter. numberStyle = . currency formatter.

How do you round a float to 2 decimal places in Swift?

Rounding Numbers in SwiftBy using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

Can you format numbers with CSS?

Is it possible to format numbers with CSS? That is: decimal places, decimal separator, thousands separator, etc. You can't but you really should be able to. After all, 50,000 or 50000 or 50,000.00 are all the same 'data' they're just presented differently which is what CSS is for.


3 Answers

There's actually much easier solution (there is no need to create NumberFormatter instance) and it takes into account the user's language:

let result = String(format: "%ld %@", locale: Locale.current, viewCount, "views")

Result for value 1000000 with English:

1,000,000

Russian:

1 000 000

p.s. in Android it's exactly the same String.format(Locale.getDefault(), "%,d %s", viewCount, "views")

like image 197
user924 Avatar answered Sep 18 '22 16:09

user924


swift 4

extension Int {
    func formatnumber() -> String {
        let formater = NumberFormatter()
        formater.groupingSeparator = "."
        formater.numberStyle = .decimal
        return formater.string(from: NSNumber(value: self))!
    }
}
like image 21
Ahmed Safadi Avatar answered Sep 18 '22 16:09

Ahmed Safadi


For leading zeros (Swift 5.2)

String(format: "%02d", intNumber) // 6 -> "06"
String(format: "%03d", intNumber) // 66 -> "066"
String(format: "%04d", intNumber) // 666 -> "0666"

from: https://stackoverflow.com/a/25566860/1064316

like image 24
norbDEV Avatar answered Sep 22 '22 16:09

norbDEV