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
Related
I have a UITextField in which the user enters an amount of money. I am trying to make the textField show the current money symbol, as the user types in an amount.
So far I was able to do that in textFieldDIdEndEditing:, how can I do the following code in a method that lets you change as the user types. (For example shouldChangeTextInRange:.) This way the currency will always show, not only when the user is finished entering the amount.
Here is what I have so far:
- (void)textFieldDidEndEditing:(UITextField *)textField {
NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setLocale:[NSLocale currentLocale]];
[currencyFormatter setMaximumFractionDigits:2];
[currencyFormatter setMinimumFractionDigits:2];
[currencyFormatter setAlwaysShowsDecimalSeparator:YES];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *someAmount = [NSNumber numberWithDouble:[textField.text doubleValue]];
NSString *string = [currencyFormatter stringFromNumber:someAmount];
textField.text = string;
}
The reason why I don't just insert it in a UILabel is because some places have their currency after the amount. (Ex. France)
Create a UIImageView with currency image.
And then set leftView either RightView of UITextField as per your requirement.
UIImage *cImage = [UIImage imageNamed:#"currency.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:cImage];
[imageView setFrame:CGRectMake(0, 0, 40, 40)];
// For Left
[textfield setLeftView:imageView];
// or
// For Right
[textfield setRightView:imageView];
Try this.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField == txtAmount) {
if ([txtAmount.text isEqualToString:#""]) {
txtAmount.text = #"$";
}else{
txtAmount.text = [NSString stringWithFormat:#"%#",txtAmount.text];
}
}
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
if (textField == txtAmount) {
if ([txtAmount.text isEqualToString:#"$"]) {
txtAmount.placeholder = #"Amount";
}
}
return YES;
}
and don't forget to give delegate to the UITextField.
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.
- (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];
}
}
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]];
I have a simple calculator app and I want it to be so that if the answer requires no decimal places, there are none, just whole numbers. If the answer was 2, I don't want it to say 2.000000, it should say 2. If it requires one decimal place, it should show to one decimal place for example 12.8 instead of 12.80. How would I do this? Here is my code.
btw, this is from a tutorial at http://www.youtube.com/watch?v=Ihw0cfNOrr4, not my own work.
viewcontroller.h
#import <UIKit/UIKit.h>
interface calcViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
#end
in the .m
#import "calcViewController.h"
#implementation calcViewController
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"%2f", currentNumber];
}
-(IBAction)buttonOperationPressed:(id)sender {
if (currentOperation ==0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:#"%2f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];
}
-(IBAction)cancelInput {
currentNumber =0;
calculatorScreen.text = #"0";
}
-(IBAction)cancelOperation {
currentNumber = 0;
calculatorScreen.text = #"0";
currentOperation = 0;
}
One way is to use NSNumberFormatter to format your result instead of NSString's -stringWithFormat::
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:requiredDigits];
[formatter setMinimumFractionDigits:0];
NSString *result = [formatter stringFromNumber:[NSNumber numberWithFloat:currentNumber];
The easiest way is just use [[NSNumber numberWithFloat:] stringValue]
Example:
float someFloatValue;
NSString floatWithoutZeroes = [[NSNumber numberWithFloat:someFloatValue] stringValue];
If we use %g in place of %f will truncate all zeros after decimal point.
For example
[NSString stringWithFormat:#"%g", 1.201000];
Output
1.201
This should work
NSString *result = [#(currentNumber) description];
I had the same problem. This is the code snippet that solved it (looks a lot like Caleb's solution, but that one didn't work for me, so I had to add an extra line):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = kCFNumberFormatterDecimalStyle;
numberFormatter.maximumFractionDigits = 20;
numberFormatter.minimumFractionDigits = 0;
NSNumber *number = [[NSNumber alloc]init];
NSString *numberString = [numberFormatter stringFromNumber:number];
We can use another numberStyle and override its basic appearance, setting desired properties of an NSNumberFormatter.