formatting currency output in ios - ios

- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (textfield1) {
NSString *txt = self.textfield1.text;
double num1 = [txt doubleValue];
double tCost = num1 /100;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];
self.textfield1.text = [NSString stringWithFormat:#"%0.#",numberAsString];
}
}
This is the code ive put together it formats the output of a textfield into currency
im trying to work out how do format the currency so the output is,
if someone types in 1625 it formats it as 0.1625
currently if somone types in 50 it formats it as 0.50 which is correct as it supposed to be a calculator which is taking in peoples electricity rates which is either in cents or pences.

To get currency formatting use the following code :
- (NSString*) getAmountInCurrencyFormatWithValue:(NSString*) valueString {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[valueString doubleValue]]];
return numberAsString;
}

(void)textFieldDidEndEditing:(UITextField *)textField
{
if (textfield1) {
NSString *txt = self.textfield1.text;
double num1 = [txt doubleValue];
double tCost = num1/100;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
// NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];
//NSString *numberAsString = [numberFormatter stringFromNumber:
// [NSNumber numberWithDouble:[tCost doubleValue]]];
[numberFormatter setMaximumFractionDigits:3];
[numberFormatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];
self.textfield1.text = [NSString stringWithFormat:#"%#",numberString];
}
}

Related

How to write NSString in a float format?

In My app I have a UITextField. When a user enters text such as 123456 it should appear something like 123,456.00 in the textfield.
The following code is used:
UITextField *txt = [[UITextField alloc]initWithFrame:CGRectMake(300, 120+y*58, 280, 31)];
txt.keyboardType = UIKeyboardTypeDecimalPad;
txt.borderStyle = UITextBorderStyleRoundedRect;
txt.font = [UIFont systemFontOfSize:15];
txt.textAlignment = NSTextAlignmentLeft;
txt.returnKeyType = UIReturnKeyDefault;
txt.delegate = self;
[txt addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
-(void)textFieldDidChange:(UITextField *)theTextField
{
NSString *textFieldText = [theTextField.text stringByReplacingOccurrencesOfString:#"," withString:#""];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *number = [formatter numberFromString:textFieldText];
NSString *formattedOutput = [formatter stringFromNumber:number];
theTextField.text=formattedOutput;
}
Use below code
NSString *textFieldText = theTextField.text ;
float f = [theString floatValue];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
[formatter setLocale:[NSLocale currentLocale]];
NSLog(#"%#", [formatter stringFromNumber:#(f)]);
Set MinimumFractionDigits to 2 & MaximumFractionDigits to 2.Try above code in textFieldDidEndEditing delegate method of textfield.
You are almost close to your solution just few things need enhancement. First you must have to specify the maximum and minimum allowed fractions digits like this:
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
It will fix the *.00 problem, then there is another problem of updating it back to the UI. Since you are setting the textfield text:
theTextField.text=formattedOutput;
It will lose the current position of editing and hence you will lose the ground. e.g.,
You typed 1, the above code will update the textfield with 1.00 and the cursor will move to position 5:
1.00
^^^^^
If you will edit further you won't get the expected result (the text will try to append at the end).
To fix this either you should update the text field when you finish editing using the handler textFieldDidEndEditing or you should use some other control like UILabel to display the formatted result.
Sample Code: (for demo)
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITextField *txt = [[UITextField alloc]initWithFrame:CGRectMake(20, 120+(3)*58, 280, 31)];
txt.keyboardType = UIKeyboardTypeDecimalPad;
txt.borderStyle = UITextBorderStyleRoundedRect;
txt.font = [UIFont systemFontOfSize:15];
txt.textAlignment = NSTextAlignmentLeft;
txt.returnKeyType = UIReturnKeyDefault;
txt.delegate = self;
[self.view addSubview:txt];
[txt addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
lbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 160+(3)*58, 280, 31)];
[self.view addSubview:lbl];
}
-(void)textFieldDidChange:(UITextField *)theTextField
{
NSString *textFieldText = [theTextField.text stringByReplacingOccurrencesOfString:#"," withString:#""];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
NSNumber *number = [formatter numberFromString:textFieldText];
NSString *formattedOutput = [formatter stringFromNumber:number];
[lbl setText:formattedOutput];
}
You can set text like this to your textview.
theTextField.text = [NSString stringWithFormat:#"%.02f", floatVal];
Hope this helps.
If you add these two lines to the code snippet you posted:
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
right after the line in which you set the number formatter's style to NSNumberFormatterDecimalStyle, it should give you exactly what you want.
#"123456" would result in #"123,456.00"
and #"1" would result in #"1.00"

How to correctly generate timestamp

I have a method that to create timestamp in long long integer format
EX: 1386752892
+ (NSNumber *)currentTimestampWithLongLongFormat
{
double timeStamp = ceil([[NSDate date] timeIntervalSince1970] * 1000);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setGeneratesDecimalNumbers:false];
NSNumber *timeNumber = [NSNumber numberWithDouble:timeStamp];
NSString *timeString = [formatter stringFromNumber:timeNumber];
// NSTimeInterval is defined as double
return [NSNumber numberWithLongLong:[timeString longLongValue]];
}
But this will generate 13 digitals number
EX: 1386752811802
How to fix the problem and generate the correct format of number?
int timestamp = [[NSDate date] timeIntervalSince1970];
Try this
/**
* #param nil
* #return current time in mili second
*
* Fetch the current time stamp
*/
-(NSString *)currentTimeStamp {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithName:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp1 = [dateFormatter stringFromDate:[NSDate date]];
NSDate *curdate = [dateFormatter dateFromString:timeStamp1];
double unix_timestamp = [curdate timeIntervalSince1970];
NSString *timeStamp = [NSString stringWithFormat:#"%f",unix_timestamp*1000];
return timeStamp;
}
+ (NSString*) dateFromString:(NSString*)aStr
{
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
[formater setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *date2 = [formater dateFromString:aStr];
[formater setDateFormat:#"d MMM,yyyy HH:mm"];
NSString *result = [formater stringFromDate:date2];
return result;
}
+ (NSString *)calculateTime:(NSString *)datetime :(NSString *)servertime
{
NSString *time;
NSDate *date1;
NSDate *date2;
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
date1 = [formatter dateFromString:datetime];
date2 = [formatter dateFromString:servertime];
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *differenceComponents = [calendar components:(NSDayCalendarUnit)
fromDate:date1
toDate:date2
options:0];
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];//[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
int hour = interval / 3600;
int minute = (int)interval % 3600 / 60;
int seconds = (int)interval % 60;
hour=ABS(hour);
minute=ABS(minute);
seconds=ABS(seconds);
if ([differenceComponents day]>0) {
time= [NSString stringWithFormat:#"%ld %#", (long)[differenceComponents day],[NSString stringWithFormat:NSLocalizedString(#"daysago", nil)]];
}
else
{
if ([differenceComponents day] == 0) {
time= [NSString stringWithFormat:#"%ld %#", (long)[differenceComponents day],[NSString stringWithFormat:NSLocalizedString(#"dayago", nil)]];
if (hour>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(hour),[NSString stringWithFormat:NSLocalizedString(#"hourago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(hour),[NSString stringWithFormat:NSLocalizedString(#"hoursago", nil)]];
if (minute>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(minute),[NSString stringWithFormat:NSLocalizedString(#"minuteago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(minute),[NSString stringWithFormat:NSLocalizedString(#"minuteago", nil)]];
if (seconds>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(seconds),[NSString stringWithFormat:NSLocalizedString(#"secondago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(seconds),[NSString stringWithFormat:NSLocalizedString(#"secondsago", nil)]];
}
}
}
}
}
return time;
}
/// as per requirement we will use date formats

Combining 2 NSDateFormatters into one

Currently I have two NSDateFormatters in my app and I want to somehow "combine" them so I only have, since they're parsing the same date.
I have a NSObject called UpcomingReleases, thats where all my JSON info gets stored.
UpcomingRelease.h
- (NSString *) formattedDate;
UpcomingRelease.m
- (NSString *) formattedDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:self.release_date];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
My UICollectionViewController (UpcomingReleasesViewController.m)
if([upcomingReleaseDictionary objectForKey:#"release_date"] != NULL)
{
NSString *readableDate = [upcomingReleaseDictionary objectForKey:#"release_date"];
UpcomingRelease *upcoming = [[UpcomingRelease alloc] init];
upcoming.release_date = readableDate;
cell.release_date.text = [NSString stringWithFormat:#"%#", upcoming.formattedDate];
}
My detailedViewController (ReleaseViewController.m)
(_singleRelease is a NSDictionary)
- (void)viewDidLoad
{
[super viewDidLoad];
if([_singleRelease objectForKey:#"release_date"] != NULL)
{
NSString *readableDate = [_singleRelease objectForKey:#"release_date"];
UpcomingRelease *singleRelease = [[UpcomingRelease alloc] init];
singleRelease.release_date = readableDate;
self.release_date.text = [NSString stringWithFormat:#"%#", singleRelease.formattedDate];
}
}
This was working fine, until I added a share on twitter action and I had to add another NSDateFormatter so it could show the readable date inside the tweet (I would get an error saying "No visible interface for ReleaseViewController declares the selected 'formattedDate'" otherwise).
- (NSString *) formattedDate:(NSString *)jsonDateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:jsonDateString];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
#pragma mark - Share on twitter
- (IBAction)shareOnTwitter:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
NSString *formattedDate = [self formattedDate:[_singleRelease objectForKey:#"release_date"]];
[tweetSheet setInitialText:[NSString stringWithFormat:#"%#", formattedDate]];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
How can I combine both these NSDateFormatters into one? They're both parsing the same string in the same way (also if there's a better way to show the formattedDate string than the one I'm currently doing would be great).
This is how my JSON shows the date string:
release_date: "2013-11-16T00:00:00.000Z"
Thanks.
As #Hot Licks says:
Make the date formatter a class method:
+ (NSString *) formattedDate:(NSString *)jsonDateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:jsonDateString];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
Put it in a utility class and use it in both cases. In the first case just pass in self.release_date.

output for a texteild is zero rather then an actual result

This is a strange output, I seem to trigger the alert view each time, and the value for num1 would be 0.50 which is fine.
When I click calculate the alert field is triggered, and what's more num1 is set to 0.00, and the tcost which is the total cost seems to always be 0.
This has never happened before.
The type out of output should be something such as a 0.23 etc.. for tcost the reason for the alert field is so i can trap if a user has not filled a field out.
(void)textFieldDidEndEditing:(UITextField *)textField
{
CGRect viewFrame = self.view.frame;
viewFrame.origin.y += animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
if (textField1) {
NSString *txt = self.textField1.text;
double num1 = [txt doubleValue];
double tCost = num1/100;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
[numberFormatter setMaximumFractionDigits:3];
[numberFormatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];
self.textField1.text = [NSString stringWithFormat:#"%#",numberString];
}
}
(IBAction)calculateCost:(UIButton *)sender {
NSString *rate = self.textField1.text;
NSString *wat = self.textField2.text;
NSString *hours = self.textField3.text;
NSString *Days = self.textField4.text;
long double num1 = [rate doubleValue];
long double num2 = [wat doubleValue];
long double num3 = [hours doubleValue];
long double num4 = [Days doubleValue];
//double num12 = num1 /10000;
double appKw = num2 / 1000;
double costKwph = appKw *num1;
double tCost = ((num4 * num3) * costKwph);
if (num2 == 0|| num1 <= 0.000|| num3 == 0 || num4 == 0) {
self.textField5.text = 0;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"oops" message:#"you must fill in all fields" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK",nil];
[alert show];
}
tCost = tCost / 100;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
[numberFormatter setMaximumFractionDigits:4];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];
self.textField5.text = [NSString stringWithFormat:#"%#",numberAsString];
}
Try to convert your textField in NSNumber, for example:
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * num1 = [f numberFromString:self.textField1.text];
if (textField == self.textField1) {
NSNumberFormatter *nFormatter = [[NSNumberFormatter alloc] init];
[nFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
self.textField1.text = [nFormatter stringFromNumber:[NSNumber numberWithFloat: [self.textField1.text doubleValue] / 100]];
}
You can not extract float from currency, hence why the result in textField5 is zero. so forma the above to output to a corresponding label so the user can see the formatted string like so.
if (textField == self.textField1) {
NSNumberFormatter *nFormatter = [[NSNumberFormatter alloc] init];
[nFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
self.labeltest.text = [nFormatter stringFromNumber:[NSNumber numberWithFloat: [self.textField1.text doubleValue] /100]];

Detect if NSString is a float number

I am trying to dectect if an NSString it's a float number, for exemple : #"-73.041382"
But when I try with this method I obtain a wrong result:
-(bool) isNumeric:(NSString*) checkText{
NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
NSNumber* number = [numberFormatter numberFromString:checkText];
if (number != nil) {
return true;
}
return false;
}
Someone have an idea!?
Thanks
I have found the answer :
-(bool) isNumeric:(NSString*) checkText{
NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
//Set the locale to US
[numberFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease]];
//Set the number style to Scientific
[numberFormatter setNumberStyle:NSNumberFormatterScientificStyle];
NSNumber* number = [numberFormatter numberFromString:checkText];
if (number != nil) {
return true;
}
return false;
}
Thanks!
-(bool) isNumeric:(NSString*) checkText{
return [[NSScanner scannerWithString:checkText] scanFloat:NULL];
}
i'm currently not on mac so i can't check it, hope it helps

Resources