Check if an NSString is a double [duplicate] - ios

This question already has an answer here:
parsing NSString to Double
(1 answer)
Closed 7 years ago.
How do I check if a UITextField's text is a double or not?
Simple validation required, if the entered textfield value is a valid double value or not?
Valid double values: 1.00, 1.01 or 1.00001
Invalid double values: .0.1, .001.11, 1.0.1 or 1...0 etc.
mytxtfield.text=#"12.00"; //ok
mytxtfield.text=#"1.2..0"; // is invalid and so on
EDIT: My answer that works thanx sahzad ali
//------------
-(BOOL)isvalidDouble:(NSString*)txtstring
{
NSArray *dotSeparratedArray = [txtstring componentsSeparatedByString:#"."];
NSInteger count=[dotSeparratedArray count];
count=count-1;
if(count >1)
{
return TRUE ; //invalid
}
return FALSE; //valid
}

You can limit user from entering multiple dots or you can use same logic in your TextFieldDidEndEditing method. If componentsSeparatedByString returns greater than 2 it means there are multiple dots.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *myString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *dotSeparratedArray = [myString componentsSeparatedByString:#"."];
if([dotSeparratedArray count] >= 2)
{
NSString *string1=[NSString stringWithFormat:#"%#",[dotSeparratedArray objectAtIndex:1]];
return !([string1 length]>1);
}
return YES;
}

I don't know whether or not this will serve your purposes, but you could use NSNumberFormatter and customize it to your needs:
NSNumberFormatter *myFormatter = [[NSNumberFormatter alloc] init];
[myFormatter setFormatWidth:7];
[myFormatter setPaddingCharacter:#"0"];
[myFormatter setMinimumSignificantDigits:0];
[myFormatter setMinimum:#0];
[myFormatter setMaximum:#9999999];
[myClientIDTextField setFormatter:myFormatter];

Related

How to add commas automatically for every 3 numbers while user input the text field - iOS Objective C [duplicate]

This question already has answers here:
How do you dynamically format a number to have commas in a UITextField entry?
(9 answers)
Closed 5 years ago.
How to add commas for every 3 numbers while user inputting the text field and also display the number with commas on the label?
I am using this function but it does not work.
- (void)commaFormatter
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setGroupingSeparator:#","];
[numberFormatter setGroupingSize:3];
[numberFormatter setDecimalSeparator:#"."];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
}
If you want a number like 123,456,789,5 then use shouldChangeCharactersInRange delegate method and write below code inside it.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *strTemp = textField.text;
strTemp = [textField.text stringByReplacingOccurrencesOfString:#"," withString:#""];
if (strTemp.length%3==0&&![string isEqualToString:#""]&&textField.text.length!=0&&![[textField.text substringWithRange:NSMakeRange(textField.text.length-1, 1)] isEqualToString:#","]) {
_txtField.text = [_txtField.text stringByAppendingString:#","];
}
return YES;
}

NSString is a number? [duplicate]

This question already has answers here:
Check that a input to UITextField is numeric only
(22 answers)
Closed 8 years ago.
I have a TextField and wanted to know if the user just pressed numbers
eg::
_tfNumber.text only has numbers?
is there any function on NSString for this?
This will let you know if all of the characters are numbers:
NSString *originalString = #"1234";
NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
NSString * trimmedString = [originalString stringByTrimmingCharactersInSet:numberSet];
if ((trimmedString.length == 0) && (originalString.length > 0)) {
NSLog(#"Original string was all numbers.");
}
Note that this ensures it won't give a false positive for the empty string, which technically also doesn't contain any non-numbers.
try this:
NSCharacterSet *_NumericOnly = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *myStringSet = [NSCharacterSet characterSetWithCharactersInString:mystring];
if ([_NumericOnly isSupersetOfSet: myStringSet]) {
NSLog(#"String has only numbers");
}
I got it from: http://i-software-developers.com/2013/07/01/check-if-nsstring-contains-only-numbers/
You can use this method in your UITextField's delegate method textField:shouldChangeCharactersInRange:replacementString: and do the verification while the user is typing.
No, but it should be easy to write:
- (BOOL)justContainsNumbers:(NSString *)str {
if ([str length] == 0)
return NO;
for (NSUInteger i = 0; i < [str length]; i++)
if (!isdigit([str characterAtIndex:i]))
return NO;
return YES;
}
Let's try regular Expression,
NSString * numberReg = #"[0-9]";
NSPredicate * numberCheck = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", numberReg];
if ([numberCheck evaluateWithObject:textField.text])
NSLog (#"Number");
No. NSString is not an NSNumber and any values you get from a UITextField will be an NSString. See THIS SO answer for converting that entered NSString value into an NSNumber.

how to validation and format input string to 1234567890 to 123-456-7890

I have to format input string as phone number.For i am using
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
if (string.length==3||string.length==7) {
filtered =[filtered stringByAppendingString:#"-"];
}
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
here
#define NUMBERS_ONLY #"1234567890-"
#define CHARACTER_LIMIT 12
but its not editing back.
Please give some ideas
The method you're using is a UITextFieldDelegate method that determines whether or not to allow a change to the text field - given the range and replacement text, should the change be made (YES or NO).
You're trying to format a string while it is being typed - for this you'll also need to update the value of the textField.text property. This could be done in the same method while returning a "NO" afterwards.
For validation,
- (BOOL) isValidPhoneNumber
{
NSString *numberRegex = #"(([+]{1}|[0]{2}){0,1}+[0]{1}){0,1}+[ ]{0,1}+(?:[-( ]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",numberRegex];
return [numberTest evaluateWithObject:self.inputString];
}
You can use this for formatting the string,
self.inputString = #"1234567890"
NSArray *stringComponents = [NSArray arrayWithObjects:[self.inputString substringWithRange:NSMakeRange(0, 3)],
[self.inputString substringWithRange:NSMakeRange(3, 3)],
[self.inputString substringWithRange:NSMakeRange(6, [self.inputString length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:#"%#-%#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];

Formating a single textfield so that it display is different to all the others

How would i set the currency in a text field to display it as a localized currency, with a leading 0. If someone types in 16.25 pence it would be formated as 0.1625£ respectively. I am using delegation and formating all text fields so only numbers can be passed in, this field should also be localized.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // First, create the text that will end up in the input field if you'll return YES:
NSString *resultString = [textField.text stringByReplacingCharactersInRange:range withString:string];
// Now, validate the text and return NO if you don't like what it'll contain.
// You accomplish this by trying to convert it to a number and see if that worked.
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* resultingNumber = [numberFormatter numberFromString:resultString];
//[numberFormatter release];
return resultingNumber != nil;
I do not want this to change, as it formats all my fields. Just want textField1 to have the relevant format,how would i go about doing this, i think it lies in viewdidload method and setting the text property to be localized to a floating point, but i cant seem to work out how to do it.
You can specify which textField you want to format in the delegate method above.
if (textField == textField1) {
// Do Something....
} else {
// Do whatever you want with the other text fields
}
For floating point formatting, use something like this -
[myTextField setText:[NSString stringWithFormat:#"%.2f", myFloat]];
(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:#"%#",numberAsString];
}
}

Having trouble using NSNumberFormatter for currency conversion in iOS

I have a UITextField that receives numeric input from the user in my application. The values from this textfield then get converted into currency format using NSNumberFormatter within my shouldChangeCharactersInRange delegate method. When I enter the number "12345678", the number gets correctly converted to $123456.78 (the numbers are entered one digit at a time, and up to this point, everything works smoothly). However, when I enter another digit after this (e.g. 9), rather than displaying "1234567.89", the number "1234567.88" is displayed. If I enter another number after that, a totally different numbers after this (I'm using the number key pad in the application to enter the numbers. Here is the code that I have:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
modifiedValue = [formatter stringFromNumber:[NSNumber numberWithFloat:[modifiedValue floatValue]]];
textField.text = modifiedValue;
The line that causes this unusual conversion is this one:
modifiedValue = [formatter stringFromNumber:[NSNumber numberWithFloat:[modifiedValue floatValue]]];
Can anyone see why this is?
It's likely to be a rounding error when doing the string->float conversion. You shouldn't use floats when dealing with currency. You could use a NSDecimalNumber instead.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
// Below 2 lines if converting from a "currency" string
NSNumber *modifiedNumber = [formatter numberFromString:modifiedValue]; // To convert from the currency string to a number object
NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithDecimal:[modifiedNumber decimalValue]];
// OR the below line if converting from a non-currency string
NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:modifiedValue];
modifiedValue = [formatter stringFromNumber:decimal]; // Convert the new decimal back to a currency string
You may also consider making the number formatter lenient - often helps with user entered data.
[formatter setLenient:YES];
When I'm running number conversions to currency, I usually run this code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *text = _textField.text;
NSString *decimalSeperator = #".";
NSCharacterSet *charSet = nil;
NSString *numberChars = #"0123456789";
// the number formatter will only be instantiated once ...
static NSNumberFormatter *numberFormatter;
if (!numberFormatter)
{
[numberFormatter setLocale:[NSLocale currentLocale]];
numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
numberFormatter.maximumFractionDigits = 10;
numberFormatter.minimumFractionDigits = 0;
numberFormatter.decimalSeparator = decimalSeperator;
numberFormatter.usesGroupingSeparator = NO;
}
// create a character set of valid chars (numbers and optionally a decimal sign) ...
NSRange decimalRange = [text rangeOfString:decimalSeperator];
BOOL isDecimalNumber = (decimalRange.location != NSNotFound);
if (isDecimalNumber)
{
charSet = [NSCharacterSet characterSetWithCharactersInString:numberChars];
}
else
{
numberChars = [numberChars stringByAppendingString:decimalSeperator];
charSet = [NSCharacterSet characterSetWithCharactersInString:numberChars];
}
// remove amy characters from the string that are not a number or decimal sign ...
NSCharacterSet *invertedCharSet = [charSet invertedSet];
NSString *trimmedString = [string stringByTrimmingCharactersInSet:invertedCharSet];
text = [text stringByReplacingCharactersInRange:range withString:trimmedString];
// whenever a decimalSeperator is entered, we'll just update the textField.
// whenever other chars are entered, we'll calculate the new number and update the textField accordingly.
if ([string isEqualToString:decimalSeperator] == YES)
{
textField.text = text;
}
else
{
NSNumber *number = [numberFormatter numberFromString:text];
if (number == nil)
{
number = [NSNumber numberWithInt:0];
}
textField.text = isDecimalNumber ? text : [numberFormatter stringFromNumber:number];
}
return NO; // we return NO because we have manually edited the textField contents.
}
The link explaining this is Re-Apply currency formatting to a UITextField on a change event
Hope this works!

Resources