Can't get a reference to NSNumberFormatter in Swift - ios

I can't figure this out, referencing this post: Struggling with NSNumberFormatter in Swift for currency
I can't get a reference to NSNumberFormatter...i.e. I can't call any methods on formatter? (the below throws an error of expected declaration)
import Foundation
class CurrencyFormatter {
var price = 100
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.stringFromNumber(price)
}

class CurrencyFormatter {
var price = 100
var formatter = NSNumberFormatter()
init() {
formatter.numberStyle = .CurrencyStyle
formatter.stringFromNumber(price)
}
}

Related

Issue in converting float to currency String formatter

Extenstion for converter Swift 4.2
extension Float {
var localeCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = .current
return formatter.string(from: self as NSNumber)!
}
}
Accessing the value
let amount = 200.02
print("Amount Saved Value ",String(format:"%.2f", amountSaving. localeCurrency))
For me Its return 0.00!
Looks to me Extenstion Perfect when accessing it return 0.00! Why?

Format values of a Pie Chart in Charts

I am using pie chart from Charts library for iOS and have been able to display the results on the chart but i am unable to format the value in that chart.
Expected Output
I want the value as £ appended before the value. Just like this - £ 10
What I've Done
class ChartValueFormatter : NSObject, IValueFormatter {
var numberFormatter : NumberFormatter?
convenience init(numberFormatter : NumberFormatter) {
self.init()
self.numberFormatter = numberFormatter
}
func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String{
return numberFormatter!.string(for: "£ \(value)")!
}
}
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale.current
let valuesFormatter = ChartValueFormatter(numberFormatter: numberFormatter)
dataSet.valueFormatter = valuesFormatter
Actual Problem
This approach is giving me error on return numberFormatter!.string(for: "£ \(value)")! and the error is because the value is nil.
Can anyone please help me on what i've done wrong and what should be done in order to get the expected output.
Please Check this:
let price:Float = 1.99
extension Float {
var asLocaleCurrency:String {
var formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = "GBP"
return formatter.string(for: self)!
}
}
let pri = price.asLocaleCurrency
print(pri)
Result: £1.99
you should use
formatter.numberStyle = .currency
not as .decimal

iOS Charts ValueFormatter

I am using iOS charts plugin (line chart) and wish to style the chart values (the number above each point) to a decimal number.
The value is a double, but charts by default is rounding it and displaying it as an integer.
I have tried the following but not working:
let valueformatter = NumberFormatter()
valueformatter.numberStyle = .decimal
valueformatter.locale = Locale.current
lineChartDataSet.valueFormatter = valueformatter as? IValueFormatter
I have tried various other properties but non of them change the format of the number in the dataset.
How can I change the format of the displayed number?
Almost there, just need to add the following class:
//For old Charts version
//class ChartValueFormatter: NSObject, IValueFormatter {
//For Charts version 4.0.1
class ChartValueFormatter: NSObject, ValueFormatter {
fileprivate var numberFormatter: NumberFormatter?
convenience init(numberFormatter: NumberFormatter) {
self.init()
self.numberFormatter = numberFormatter
}
func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
guard let numberFormatter = numberFormatter
else {
return ""
}
return numberFormatter.string(for: value)!
}
}
Now use this as the number formatter:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale.current
let valuesNumberFormatter = ChartValueFormatter(numberFormatter: numberFormatter)
lineChartDataSet.valueFormatter = valuesNumberFormatter
lineChartDataSet.valueFont = lineChartDataSet.valueFont.withSize(chartFontPointSize)
lineChartDataSet.valueFormatter = DefaultValueFormatter(decimals: 2)
This worked for me:
Swift 5
let valFormatter = NumberFormatter()
valFormatter.numberStyle = .currency
valFormatter.maximumFractionDigits = 2
valFormatter.currencySymbol = "$"
lineChartPrice.leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: valFormatter)
let data = PieChartData(dataSet: set)
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumFractionDigits = 2
formatter.multiplier = 1.0
formatter.percentSymbol = "%"
formatter.zeroSymbol = ""
data.setValueFormatter(DefaultValueFormatter(formatter: formatter))

How to use currencyFormatter with a decimal

I'm trying to take a decimal I'm storing in CoreData and run it through the currency formatter in Swift 3. Here is what I'm trying to use:
var currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = NumberFormatter.Style.currency
// localize to your grouping and decimal separator
currencyFormatter.locale = NSLocale.current
var priceString = currencyFormatter.stringFromNumber(NSNumber(totalAmount))
Where totalAmount is the decimal I'm using for CoreData.
But . I get this error when trying to convert my decimal to a NSNumber()
Argument labels '(_:)' do not match any available overloads
stringFromNumber got renamed to string(from:), e.g.
var priceString = currencyFormatter.string(from: NSNumber(totalAmount))
but you don't have to convert to NSNumber
var priceString = currencyFormatter.string(for: totalAmount)
You can have something like:
class YourClass: UIViewController {
static let priceFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.formatterBehavior = .behavior10_4
formatter.numberStyle = .currency
return formatter
}()
}
Usage:
yourLabel.text = YourClass.priceFormatter.string(from: totalAmount)

Format NSString using NSFormatter

I am getting price of an object in string and I want to formate it as currency.
I am using the following code:
var priceString : NSString = urlDict.objectForKey("price") as NSString
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = NSLocale.currentLocale()
let priceNumber = formatter.numberFromString(priceString)
I am getting the data fine in priceString but priceNumber is nil.
And if I try this:
var priceNumber : NSNumber = urlDict.objectForKey("price") as NSNumber
then also the priceNumber is nil.
What approach should I take to achieve a formatted price from the string?
Thanks all for the suggestions:
I have combined above solutions to form a function:
func formatAsPrice(priceString: NSString) -> NSString {
let rsSymbol = "\u{20B9}" // The currency symbol for India
var priceStrTemp = priceString
priceStrTemp = rsSymbol + priceStrTemp
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = NSLocale.currentLocale()
formatter.locale = NSLocale(localeIdentifier: "en_IN") //Explicit
formatter.secondaryGroupingSize = 2 // grouping as Indian currency style
let priceNumber = formatter.numberFromString(priceStrTemp)!
var finalPrice: NSString! = (rsSymbol + " \(priceNumber)") as NSString!
return finalPrice
}
The Formatter code is fine.
You have to pass correct Currency string with currency symbol
func format(amount: String) -> NSNumber? {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = NSLocale.currentLocale()
return formatter.numberFromString(amount)
}
format("NOK 12,00") // returns 12.00
format("NOK 12") // Also fine
format("$ 12") // Error, my local currency is NOK (Norwegian krone)
format("12,00") // Error, needs currency symbol in the string.
If you want to parse trying without currency sublime like this "12,00" that you should set currencySymbol to empty string. Like this
func format(amount: String) -> NSNumber? {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.currencySymbol = ""
...
}
format("12,00") // Works fine now

Resources