Use keypad to enter in currency value in desired format - iphone

I want to have a screen that starts off with "$0.00" (or other symbol based on locale) that I can enter values into and it will update one at a time. (type 1234, returns $0.01, $0.12, $1.23, $12.34).
I know how to do this with the digits entered into a text field and with the click of a button change the formatting either in the text field or into a new label. What I want, though, is to do it without the extra button tap and use a label, not a textField.
float moneyEarnedFloat = [revenueTextField.text floatValue]/100.0f;
NSNumber *moneyEarned = [NSNumber numberWithFloat:moneyEarnedFloat];
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
revenueTextField.text = [currencyFormatter stringFromNumber:moneyEarned];
An example would be mint.com's Add Transaction screen.

Try this:
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
int currencyScale = [currencyFormatter maximumFractionDigits];
TextFieldDidChange:
[mytextField addTarget:self action:#selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
Then do:
- (void)textFieldDidChange {
myLabel.text = mytextField.text;
}

Related

Display an integer with a comma: 30000 --> 30,000

How do I display an integer within a UILabel with a comma?
Like this:
30000 --> 30,000
My English is not that good so I did not know what to search for.
Thank you for your answers.
Use the NSNumberFormatter and do just few things as :
NSInteger integerValue=30000;
NSNumberFormatter *numberFormatterComma = [NSNumberFormatter new];
[numberFormatterComma setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *formatted = [numberFormatterComma stringFromNumber:[NSNumber numberWithInteger:integerValue]];
NSLog(#"--> %#",formatted);
Now you can put the formatted string to your label.
You want to look at NSNumberFormatter
Here is an example
self.numberFormat = [[NSNumberFormatter alloc] init];
//set up formatter for display text
[self.numberFormat setNumberStyle:NSNumberFormatterDecimalStyle];
[self.numberFormat setRoundingMode:NSNumberFormatterRoundFloor];
[self.numberFormat setMinimumFractionDigits:0];
[self.numberFormat setMinimumIntegerDigits:1];
[self.numberFormat setMaximumFractionDigits:24];
[self.numberFormat setMaximumSignificantDigits:24];
NSString* formattedText =
[self.numberFormat stringFromNumber:[self.numberFormat numberFromString:rawString]];
Take care not to alloc/init them often, they are quite heavy objects. Best to create once and keep in a property for reuse. If you are making OSX apps (as opposed to ios) you get formatting objects in Interface Builder also, you can drag them around and set their parameters in the attributes inspector.
// Comma seperated numeric conversion
-(NSString*)convertNumericIntoCommaSeperatedValue:(NSString*)string{
NSNumberFormatter *frmtr = [[NSNumberFormatter alloc] init];
[frmtr setGroupingSize:3];
[frmtr setGroupingSeparator:#","];
[frmtr setUsesGroupingSeparator:YES];
NSString *commaSeperatedString = [frmtr stringFromNumber:[NSNumber numberWithLongLong:[string longLongValue]]];
[frmtr release],frmtr=nil;
return commaSeperatedString;
}

NSNumberFormatter's multiplier rounds down instead of showing fraction

I have configured an NSNumberFormatter to convert amounts that are stored as cents in an NSDictionary to euro's. Because they're stored as cents, I have set the formatter's multiplier to [NSNumber numberWithDouble:0.01]. However, when I try to display 304 euro cents as euro's I get € 3,00.
This leads me to believe that the multiplier is doing integer division instead of double division.
NSFormatter configuration
/**
Returns an NSNumberFormatter that can be used to display currency in euro's (as determined in The Netherlands).
*/
+ (NSNumberFormatter *)euroCurrencyFormatter
{
static NSNumberFormatter *numberFormatter = nil;
#synchronized(self) {
if (!numberFormatter) {
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setMultiplier:[NSNumber numberWithDouble:0.01]];
NSLocale *nlLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"nl_NL"];
[numberFormatter setLocale:nlLocale];
[nlLocale release];
}
}
return numberFormatter;
}
Calling the NSFormatter
cell.detailTextLabel.text = [[NSNumberFormatter euroCurrencyFormatter] stringFromNumber:[breakdown valueForKey:#"VatAmount"]]; // The VAT amount would be 304.
Result
€ 3,00
How can I stop errounous behaviour?
Try this code.
cell.detailTextLabel.text = [[NSNumberFormatter euroCurrencyFormatter] stringFromNumber:[NSNumber numberWithDouble:[[breakdown valueForKey:#"VatAmount"] doubleValue]]]; // The VAT amount would be 304.
As if you pass VAT as a integer you will get the number always in int format.
See the "Configuring Rounding Behavior" of the NSNumberFormatter reference.

How to display float values like $0.00 in textfield in iphone?

Im new to iphone, i have one textfield, when i click custom number button the value will print in the textfield, If i enter a value in textfield Example(1234), but i want float value like 0.00. how?
Example
text1.text = [[NSString alloc] initWithFormat:#"%#%d", text1.text, num.tag];
1234
You may try this
text1.text = [NSString stringWithFormat:#"$%0.2f", 1234];
Here you can replace 1234 with the variable you want
You should see NSNumberFormater.
NSNumberFormatter *numberFormatter=[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setMinimumFractionDigits:2];
[text1 setText:[numberFormatter stringFromNumber:[NSNumber numberWithFloat:[text1.text floatValue]]];

UIKeyboardTypeDecimalPad - change comma to dot

I use this method to show keyboard with decimal separator
myTextField.keyboardType=UIKeyboardTypeDecimalPad;
How can I change comma to dot separator?
I have a Finnish locale. With comma, decimals doesn't work on my app.
-(IBAction)calculate {
float x = ([paino.text floatValue]) / ([pituus.text floatValue]) *10000;
label.text = [[NSString alloc] initWithFormat:#"%0.02f", x];
}
OK so you edit a text field using a numeric keyboard, which is dependent on the current locale, and thus get a text representation of a number, which is dependendt on the current locale, too. After editing has finished you read it and want to transform into a number.
To convert you would use NSNumberFormatter like this:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
You can setup the formatter as you will, setting locale (!), limits, formatting, decimal/grouping separator, number of decimal digits etc. Then you just use it:
float number = [nf numberFromString: field.text];
And that's all! Now you have the number even if the text includes comma, provided you let both: keyboard and formatter, to have the same format, same style - i.e. probably just let current locale be used all over the place.
EDIT
this is a currency formatter, that can convert between string and number for currencies:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle: NSNumberFormatterCurrencyStyle];
[nf setRoundingMode: NSNumberFormatterRoundHalfUp];
[nf setMaximumFractionDigits: 2]
this is a percentage formatter with 4 decimal places:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle: NSNumberFormatterPercentStyle];
[nf setRoundingMode: NSNumberFormatterRoundHalfUp];
[nf setMaximumFractionDigits: 4];
both in the current locale.
As you see you can define the style, digits, rounding behaviour and much more, depending on numbers you are trying to enter. For more details (it is really a lot you can do with the NSNumberFormatter) you should read Apple docs, it would go beyond the scope of SO answer to describe it all.
In your case, provided that paino and pituus are also UITextFields:
-(IBAction)calculate {
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setRoundingMode: NSNumberFormatterRoundHalfUp];
[nf setMaximumFractionDigits: 2];
float npaino = [[nf numberFromString: paino.text] floatValue];
float npituus = [[nf numberFromString: pituus.text] floatValue];
float x = npaino] / npituus *10000;
label.text = [nf stringFromNumber: [NSNumber numberWithFloat: x]];
[nf release];
}
Now to avoid creating the formatter in each calculation you could make it an instance variable, since you need only one for those conversions.
Easyer that way:
[[yourField text] stringByReplacingOccurrencesOfString:#"," withString:#"."]
It will work in all ways and languages.
In your code, it will be:
-(IBAction)calculate {
float fPaino = [[paino.text stringByReplacingOccurrencesOfString:#"," withString:#"."] floatValue];
float x = fPaino / ([pituus.text floatValue]) *10000;
label.text = [[NSString alloc] initWithFormat:#"%0.02f", x];
}
Something else: are you sure to need an "alloc" for the result? As the label.text contains already its retain/release, you can simply make a [NSString stringWithFormat:#"%0.02f", x]

localizing currencies in iphone app

I am testing my app. All is working fine except when I change locales to Germany.
Basically you input 2 values in your local currency, a calculation happens and the user gets info back.
Users numeric inputs are handled well. That is, on "Editing Did End" a method executes that converts the number to its local currency equivalent. So if US users enters 10000 they will be returned $10,000.00. Here's the code:
- (NSMutableString *) formatTextValueToCurrency: (NSMutableString *) numberString {
NSNumber *aDouble = [NSNumber numberWithFloat: [numberString floatValue]];
NSMutableString *aString = [NSMutableString stringWithCapacity: 20];
NSLocale *theLocale;
NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
[currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
theLocale = [NSLocale currentLocale];
[currencyStyle setLocale: theLocale];
[aString appendString: [currencyStyle stringFromNumber:aDouble]];
[currencyStyle release];
return aString;
}
However a problem occurs when I want to process the above currency values to get the user his/her info. That is, the app will now needs to get 10000 from $10,000.00 (or whatever currency) to send into the calculation method. Here's the code:
- (float) getValueFromCurrency: (id) sender {
NSNumber *aDouble = [NSNumber numberWithFloat: 0.0];
UITextField *textField = (UITextField *) sender;
NSMutableString *aString= [NSMutableString stringWithCapacity: 20];
NSLocale *theLocale;
float result;
NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
[currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
theLocale = [NSLocale currentLocale];
[currencyStyle setLocale: theLocale];
NSLog(#"The locale is %#", currencyStyle.locale.localeIdentifier);
//Above NSLog looks good because it returns de_DE
[aString appendString: textField.text];
//The append from text field to string is good also
aDouble = [currencyStyle numberFromString: aString];
//For some reason, nil is returned
result = [aDouble floatValue];
[currencyStyle release];
return result;
}
For some reason the US, UK, Japanese and Irish locales are fine.
Continental European countries are not working.
Any advice on how to fix this would be great.
Given the code works for the US, UK, Japan and Ireland but not mainland Europe (Germany) I would check how you are handling the thousands and the decimal seperator.
That is, in the countries which work for your code the thousands seperator is the comma and the decimal is the point (full stop). So 10000 dollars and 50 cents would be 10,000.50.
In mainland Europe (Germany etc) the thousands seperator is the point (full stop) and the decimal seperator is the comma. So the above value in Germany would be 10.000,50
NSNumberFormatter has two methods you might want to look at:-
(NSString *)currencyDecimalSeparator
(NSString *)currencyGroupingSeparator
You can find a list of countries in WIKI (http://en.wikipedia.org/wiki/Decimal_separator) for each of the formats and test to see if your problem is for one group only or not.
I hope that helps.
Cheers,
Kevin