I am new in swift and I want to write the number with commas
NSNumberFormatter().numberFromString("123456789")) as! String
I have error Cannot convert value of type 'Int' to expected argument type 'String'.
Any help please
Try this one.
let myNumber = 123456789
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
numberFormatter.stringFromNumber(myNumber)!
You can set the number of fractions with:
let numberToConvert: Int = 123456789
let numberFormatter = NSNumberFormatter()
numberFormatter.minimumFractionDigits = 2
let convertedNumber = numberFormatter.stringFromNumber(numberToConvert)
prints
"123456789.00"
If you want something like "123,456,789" then add following line after minimumFactionDigits
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
var string= "7890"
var number = Int(string)
If u don't need to specify number of decimal places:
var number: CGFloat = 98888.5555
var string = "\(number)"
Related
I need a specific behaviour from my NumberFormatter used to output currency:
If the number is integer (0, 0.00) it should not show decimal separator (0 €)
Else (123.90, 12.1), it should show two digits after decimal separator (123.90 €, 12.10 €).
The way I create and use my formatter now is the following:
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = "€"
formatter.alwaysShowsDecimalSeparator = false
let num = formatter.string(from: 123.9)!
If created like this, the formatter always shows decimal separator, despite the fact that I set this property to false.
How can I achieve this?
Currency numberStyle is always returning decimal point followed two digits. So if you want to achieve your goal, you should modify the output string by yourself.
Please check the example code:
let number1: Double = 123.908392857
let number2: Int = 123
let number3: Float = 123.00
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = "€"
let num1 = formatter.string(from: NSNumber(value: number1))! // Output €123.91
let num2 = formatter.string(from: NSNumber(value: number2))! // Output €123.00
let num3 = formatter.string(from: NSNumber(value: number3))! // Output €123.00
print("\(num1) \(num2) \(num3)")
// This is trick
let newNum1 = trimString(string: num1) // Output €123.91
let newNum2 = trimString(string: num2) // Output €123
let newNum3 = trimString(string: num3) // Output €123
print("\(newNum1) \(newNum2) \(newNum3)")
trimString is a simple trim function, you can put it in the String extension or any place you want.
func trimString(string: String) -> String {
if string.hasSuffix(".00") {
return String(string.dropLast(3))
}
else {
return string
}
}
You may have question about why alwaysShowsDecimalSeparator is not working then? It is for .decimal numberStyle and default decimalSeparator is "."
I'm new to code and after reviewing a few answers still need a hand with this.
In my code:
func labelInformation(){
numLabels.text = newLabel.text
}
Current result:
228500.23
Desired result:
228,500.23
How/where do I use NSNumberFormatter?
Try like this:
let inputValue = 228500.23
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .CurrencyStyle
numberFormatter.currencySymbol = ""
let outputString = numberFormatter.stringFromNumber(inputValue) ?? "0.00"
print(outputString) // 228,500.23
From the code below I want convertedN to be to be 99999999 but instead I get 99999998. The problem is that there is a rounding error before I set n. What can I do to get the result I want?
let amount = ".99999999"
let tmpFormatter = NSNumberFormatter()
tmpFormatter.maximumFractionDigits = 8
let n = tmpFormatter.numberFromString(amount)
let decimalAmount = NSDecimalNumber(decimal: n!.decimalValue)
let convertedN = (decimalAmount.decimalNumberByMultiplyingBy(NSDecimalNumber(unsignedLongLong: 100000000))).unsignedLongLongValue
Use doubleValue instead. NSDecimalNumber is rounding the numbers.
let amount = ".99999999"
let tmpFormatter = NSNumberFormatter()
tmpFormatter.maximumFractionDigits = 8
let n = tmpFormatter.numberFromString(amount)
let doubleValue = n!.doubleValue
let convertedN = doubleValue * 100000000
Try like this:
let amount = ".99999999"
let decimalAmount = NSDecimalNumber(string: amount)
let convertedN = decimalAmount.decimalNumberByMultiplyingBy(NSDecimalNumber(string: "100000000")).unsignedLongLongValue // 99,999,999
I am trying to convert a given double into scientific notation, and running into some problems. I cant seem to find much documentation on how to do it either. Currently I am using:
var val = 500
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.ScientificStyle
let number = numberFormatter.numberFromString("\(val)")
println(number as Double?)
// Prints optional(500) instead of optional(5e+2)
What am I doing wrong?
You can set NumberFormatter properties positiveFormat and exponent Symbol to format your string as you want as follow:
let val = 500
let formatter = NumberFormatter()
formatter.numberStyle = .scientific
formatter.positiveFormat = "0.###E+0"
formatter.exponentSymbol = "e"
if let scientificFormatted = formatter.string(for: val) {
print(scientificFormatted) // "5e+2"
}
update: Xcode 9 • Swift 4
You can also create an extension to get a scientific formatted description from Numeric types as follow:
extension Formatter {
static let scientific: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .scientific
formatter.positiveFormat = "0.###E+0"
formatter.exponentSymbol = "e"
return formatter
}()
}
extension Numeric {
var scientificFormatted: String {
return Formatter.scientific.string(for: self) ?? ""
}
}
print(500.scientificFormatted) // "5e+2"
The issue is that you are printing the number... not the formatted number. You are calling numberForString instead of stringForNumber
var val = 500
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.ScientificStyle
let numberString = numberFormatter.stringFromNumber(val)
println(numberString)
Slight modification to the answer by leo-dabus to Xcode 9 Swift 4:
extension Double {
struct Number {
static var formatter = NumberFormatter()
}
var scientificStyle: String {
Number.formatter.numberStyle = .scientific
Number.formatter.positiveFormat = "0.###E+0"
Number.formatter.exponentSymbol = "e"
let number = NSNumber(value: self)
return Number.formatter.string(from :number) ?? description
}
}
I have used below code successfully to format Int with thousand separators. However my current project required Int64 to be formatted the same way and it throws error 'Int64' is not convertible to 'NSNumber'
var numberFormatter: NSNumberFormatter {
let formattedNumber = NSNumberFormatter()
formattedNumber.numberStyle = .DecimalStyle
formattedNumber.maximumFractionDigits = 0
return formattedNumber
}
You mean when you call numberFormatter.stringFromNumber(12345678) after the above code, like this?
let i64: Int64 = 1234567890
numberFormatter.stringFromNumber(i64)
Doesn’t look like Swift will cast from an Int64 to an NSNumber:
let i = 1234567890
let n = i as NSNumber // OK
numberFormatter.stringFromNumber(i) // Also OK
// Compiler error: 'Int64' is not convertible to 'NSNumber'
let n64 = i64 as NSNumber
// so the implicit conversion will also fail:
numberFormatter.stringFromNumber(i64)
This is a bit confounding, since Swift Ints are themselves usually the same size as Int64s.
You can work around it by constructing an NSNumber by hand:
let n64 = NSNumber(longLong: i64)
BTW beware that var trick: it’s nice that it encapsulates all the relevant code for creating numberFormatter, but that code will run afresh every time you use it. As an alternative you could do this:
let numberFormatter: NSNumberFormatter = {
let formattedNumber = NSNumberFormatter()
formattedNumber.numberStyle = .DecimalStyle
formattedNumber.maximumFractionDigits = 0
return formattedNumber
}()
If it’s a property in a struct/class, you could also make it a lazy var which has the added benefit of only being running if the variable is used, like your var, but only once.
struct Thing {
lazy var numberFormatter: NSNumberFormatter = {
println("blah")
let formattedNumber = NSNumberFormatter()
formattedNumber.numberStyle = .DecimalStyle
formattedNumber.maximumFractionDigits = 0
return formattedNumber
}()
}
extension Formatter {
static let decimalNumber: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
}
extension Numeric {
var formatted: String { Formatter.decimalNumber.string(for: self) ?? "" }
}
let x: Int64 = 1000000
x.formatted // "1,000,000"