TextBox To Double Then Show as String AlertView - iphone

I am having trouble getting a double to show up in my alert view. The string keeps showing up as 0 in the AlertView. Thanks in advance!
double binRadius = [txtRadiusInches.text doubleValue] / 12 + [txtRadiusFeet.text doubleValue];
NSString *myString = [NSString stringWithFormat:#"%d", binRadius];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Estimatated Amount"
message:myString
delegate:self
cancelButtonTitle:#"Continue"
otherButtonTitles:#"Clear All", nil];
[alert show];

%d (and %i) is the format specifier for integers (decimals). For floating point numbers you should use %f.

Related

how would i set this app up to accept localized currency and output to that currency

Hi I'm trying to set up localization to my app, it currently recieves strings from a textbox, and converts them to a double. Then it proceeds to do a calculation and output that as a string onto the screen
What I am trying to do is,
have the app know they are from a particular country convert the string to local currency ,
do the calculations, then output it in the relevant currency,
I think the solution lies nsformatter. I have been looking through documentation and im lost, here is my code, what would you guys suggest any help would be welcome.
(IBAction)calculateCost:(UIButton *)sender {
NSString *rate = self.textField1.text;
NSString *wat = self.textField2.text;
NSString *hours = self.textField3.text;
NSString *Days = self.textField4.text;
double num1 = [rate doubleValue];
double num2 = [wat doubleValue];
double num3 = [hours doubleValue];
double num4 = [Days doubleValue];
double appKw = num2 / 1000;
double costKwph = appKw *num1;
double tCost = ((num4 * num3) * costKwph);
if (num2 == 0 || num1 == 0 || 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;
self.textField5.text = [NSString stringWithFormat:#"£%0.2f",tCost];
}
NSNumberFormatter includes a currency style, which is locale-safe, but not thread-safe, so they should't be modified from different threads. An example follows:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:tCost/100.00]];

Show UIAlert if UITextField is empty

All I want to do, If there is nothing on UITextField , application will show an alert. I don't understanding what's wrong I'm doing. here is my code:
- (IBAction)Calculate:(id)sender {
/*If there is nothing on textfield, it will show an alert*/
if ([addtake.text length] && [Subtake.text length] == 0)
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"Alert"message:#"Empty TextField not allowed" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil];
[myAlert show];
}
else{
NSString *Adding =[addtake text];
NSInteger number = [Adding intValue]; /*Converting String to int*/
NSInteger new = 5 + number;
NSString *newString = [NSString stringWithFormat:#"%d",new];
[myAdd setText:newString];
/*Subtruct*/
NSString *Subtruct =[Subtake text];
NSInteger SubNumber = [Subtruct intValue];
NSInteger newSub = 10 - SubNumber;
NSString *newSubString = [NSString stringWithFormat:#"%d",newSub];
[mySub setText:newSubString];
[addtake resignFirstResponder];
[Subtake resignFirstResponder];
}
}
Try making each sub-clause in your if statement explicit - if only for readability...
I would use logical OR, not logical AND in your test. So that if either text field is empty the alert would show
if ((![addtake.text length]) || (![Subtake.text length]))
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"Alert"message:#"Empty TextField not allowed" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil];
[myAlert show];
}
if ([addtake.text length] == 0 && [Subtake.text length] == 0)
I assume that addText is your tesxField so you need to set the condition [addtake.text length] == 0 aswell.

how to show alert when user enter other then number value in textfield

I have iphone app in which i enter any number value like 10 2 0 1 0.2 etc i want that instead of this if user enter any text it should alert that enter a number.
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Value Must Be In Number " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
try this code:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField==txtMobileNo)
{
[self validatePhone];
}else
{
[textField resignFirstResponder];
}
// called when 'return' key pressed. return NO to ignore.
return YES;
}
- (BOOL) validatePhone
{
NSString *phoneRegex = #"^+(?:[0-9] ?){6,14}[0-9]$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
if ([phoneTest evaluateWithObject:txtMobileNo.text] == YES)
{
NSLog(#"proper phone nO ");
return YES;
}
else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:#"Please,Enter Your Person proper phone no" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil ];
[alert show];
[alert release];
NSLog(#"phone no. not in proper format");
return NO;
[txtMobileNo becomeFirstResponder];
}
}
I hope you helpful.
That disrupts the app kind of, doesn't it? What you want to look at is the UITextfield delegate methods. Set your viewController as the textields delegate and make it respond o UITextFieldDelegate protocol.
I would implement the textField:shouldChangeCharactersInRange:replacementString method and check the replacementString for unwanted characters.
But rather than displaying an alert, I guess I would just return NO if unwanted characters are contained there. Then, when the user enters something other than what you want, nothing happens.
you can check if it is a number using the following:-
NSString *yourString= #"121212";
NSCharacterSet *decimalNUmSet= [NSCharacterSet decimalDigitCharacterSet];
BOOL isNum= ([[yourString stringByTrimmingCharactersInSet:decimalNUmSet] isEqualToString:#""] ||
[[yourString stringByTrimmingCharactersInSet:decimalNUmSet] isEqualToString:#"."]);
here the second part includes decimal numbers also.
the other way is to present a numeric keyboard to user so that he can type only numbers.
You validate the entered character and do your logic in this delegate ,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// your logic to restriction goes here.like check the entered char and through alert
}
-(BOOL) validateNumericValue:(NSString*) textValue
{
NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
NSNumber* number = [numberFormatter numberFromString:textValue];
if (number != nil)
{
return YES;
}
return NO;
}

Detecting if NSNumber is between 0 and 255

I am trying to detect whether a NSNumber is between 0 and 255 or not. Whenever I run the app, I receive the alert view that my number is greater than 255, even when it is not. I do not have this problem with 0.
if (redValue < 0) {
NSLog(#"Red value is less than 0");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Your number must be greater than 0." message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
} else if (redValue > 255) {
NSLog(#"Red value is greater than 255");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Your number must be less than 255." message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
Additionally, I receive this warning on the "else if (redValue > 255)" line: Ordered comparison between pointed and integer ('NSNumber *' and 'int'), So I'm assuming I have to convert this NSNumber to an integer?
Should be:
if([redValue intValue] < 0) {
...
if([redValue intValue] > 255) {
...
Assuming it is an int. If it isn't go to the NSNumber Class Reference look under "Accessing Numeric Values" and replace intValue with the appropriate thing.
use intValue to get the number as an int:
[redValue intValue]
try this
[redValue intValue] > 255
if (redValue.intValue >255)
{
// it's greater than 255
}

Making selectedSegmentIndex select nothing after selection

I have a UISegmentControl that select nothing through IB, after the user selects the segment it becomes selected. How do i do it so that it doesnot gets selected?
//Show question method
-(void)question:(NSInteger)i
{
// Path to the plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"Question" ofType:#"plist"];
// Set the plist to an array
NSArray *array = [NSArray arrayWithContentsOfFile:path];
//Check the number of entries in the array
NSInteger numCount = [array count];
if(i <numCount)
{ NSDictionary *dict = [array objectAtIndex:i];//load array index 0 dictionary data
self.title = [NSString stringWithFormat:#"Question %d", i+1];//set the nav bar title
quest.text = [dict valueForKey:#"Question"];//Set the Question to storage
ans.text = [dict valueForKey:#"Answer"];//Set the Answer to storage
NSInteger option = [[dict valueForKey:#"NumberOfOption"] integerValue ];//Check options to determine the question type
//check if the option is is a QRCode or Multiple Choices Question
if (option ==0)
{
QRbutton.alpha = 1; //show the QR Code Button If there is no options
OptionsAnswer.alpha = 0;//Hide Option if there is no options
}
else
{
QRbutton.alpha = 0.0;//Hide QR Code Button if there is options
OptionsAnswer.alpha = 1;//Show Option if there is options
[OptionsAnswer setTitle:[dict valueForKey:#"Option1"] forSegmentAtIndex:0];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option2"] forSegmentAtIndex:1];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option3"] forSegmentAtIndex:2];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option4"] forSegmentAtIndex:3];//Set Option Answer Value
[OptionsAnswer addTarget:self action:#selector(OptionAnswerCheck) forControlEvents:UIControlEventValueChanged];//Call action when options is being selected
}
}
else {
//if question is all answered, it will prompt an alert for end game video.
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Well Done"
message:#"You Have Answered All The Questions, Oh Wait A Minute I Heard A Cracking Sound...." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
}
//Check if the selected Option is correct
-(IBAction)OptionAnswerCheck
{
//define a persistant location to save which question has been answered
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];//question storages
//pass the value from the selected option to a string
//NSString * selectedTitle = ([OptionsAnswer selectedSegmentIndex] >= 0) ? [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]] :
NSString * selectedTitle = [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]];
NSLog(#"Selected Title = %#",selectedTitle);//test
//check if the selected value is equal to the answers
if ([selectedTitle compare:self.ans.text] ==NSOrderedSame)
{
//Popup to say answer Correct
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Correct!"
message:#"Nice Work, Lets Move On To The Next Question" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
//increase the question number
[self question:++currentQuestion];
//save increased question
[userDefaults setInteger:currentQuestion forKey:#"currentQuestion"];
}
else
{
//Popup to say answer Wrong
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Incorrect"
message:#"Close! But That's Not Right, Try Another Answer" delegate:nil
cancelButtonTitle:#"Try Again." otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
//OptionsAnswer.selectedSegmentIndex = UISegmentedControlNoSegment;
}
Just search for setMomentary: in your developer documentation inside Xcode.
I'm not entirely sure what you're asking here, but I think that you want to set the momentary property toYES.
The property is in the inspector of IB as well. (Can't post a screenshot, I'm on my iPhone).