How to check if contents of a string are numeric values? - objective-c

I have seen this question but it is 2 years old. Is there a better\easier\newer way to check if string has numeric values. e.g 1 or 1.54 or -1 or -1.54 etc etc.

bool status;
NSScanner *scanner;
NSString *testString;
double result;
scanner = [NSScanner scannerWithString:testString];
status = [scanner scanDouble:&result];
status = status && scanner.scanLocation == string.length;
If status == YES then the string is fully numeric.
Or as #Dave points out from this SO answer:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
number = [formatter numberFromString:string];
status = number != nil;
(I'm not leaking, I'm using ARC :-))

you can use [NSString floatValue]

Related

Extract only DIGIT in Objective c [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have string this, Total Bill : $22.00, I just want to extract 22 from this string, i'm confused how to get that, I have tried some code but it gives me 2200 rather than 22. My code is this,
NSString * val = #"Total Bill : $22.00";
NSString *newString = [[val componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
NSLog(#"VV %#",newString);
The simplest is to find the location of the $ and then return the rest of the string. This will give you the 22.00.
NSString *val = #"Total Bill : $22.00";
NSRange dollar = [val rangeOfString:#"$"];
NSRange decimal = [val rangeOfString:#"."];
if (dollar.location != NSNotFound && decimal.location != NSNotFound) {
NSRange range = NSMakeRange(dollar.location + 1, decimal.location - dollar.location - 1)
NSString *amount = [val substringWithRange:range];
NSLog(#"VV %#",amount);
} else {
NSLog(#"No dollar sign or decimal found");
}
One option is to use a NSCharacterSet union with the characters you want to keep (currency separator -- decimal point in your case).. then invert it. Split the string and then join it using this character set. Then you can use NSNumberFormatter to get the result..
NSString *stringToParse = #"Total Blah: $22.00";
NSMutableCharacterSet *characterSet = [NSMutableCharacterSet decimalDigitCharacterSet];
[characterSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:#".,"]];
stringToParse = [[stringToParse componentsSeparatedByCharactersInSet:[characterSet invertedSet]] componentsJoinedByString:#""];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:0];
[formatter setMaximumFractionDigits:0];
[formatter setPartialStringValidationEnabled:YES];
NSString *str = [formatter stringFromNumber:[formatter numberFromString:stringToParse]];
NSLog(#"%#", str);
You can use NSScanner to extract values like this from a string.
Depending on the type you want, you can use scanDouble:, scanInt: or something else. Here's an example:
NSString *myString = #"Total Bill : $22.00";
NSScanner *scanner = [[NSScanner alloc] initWithString:myString];
// Moves the scanner to the "$" character, then eats that character
[scanner scanUpToString:#"$" intoString:nil];
[scanner scanString:#"$" intoString:nil];
// Here you have options, can scan as a double or an integer, or convert later.
double val = 0;
[scanner scanDouble:&val];

How can I be certain that a NSString is really an int?

I'm trying to validate that an NSString is an int. I have the following code to attempt this:
if([[NSScanner scannerWithString:stringValue] scanInt:nil]){
//...
}
However, if the stringValue is #"1.0something" this will still return a YES boolean to check if my NSString is an int.
Is there a way to be more accurate than this?
One possible solution is to convert the int back to an NSString and see if it matches the original string.
NSString *oldStr = ... // your original string
NSString *newStr = [NSString stringWithFormat:#"%d", [oldStr intValue]];
if ([newStr isEqualToString:oldStr]) {
// the string is a valid int value
}
You can also expand your NSScanner check and ensure the scanner is at the end after you call scanInt:.
NSScanner *scanner = [NSScanner scannerWithString:stringValue];
if ([scanner scanInt:nil] && [scanner atEnd]) {
// valid int string
}
Or you can make sure the string only contains the characters 0-9:
if ([stringValue rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet]].location == NSNotFound) {
// valid int
}
Or you can use a regular expression.
check like this
NSScanner* scan = [NSScanner scannerWithString:stringValue];
int val;
return [scan scanInt:&val] && [scan isAtEnd];
You can use NSNumberFormatter to determine if the string is a valid number:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
[formatter numberFromString:#"1.0"]; // returns #(1)
[formatter numberFromString:#"1.0something"]; // returns nil
Since partial string validation is not enabled by default, it will reject strings that don't entirely validate as a number.

NSNumberFormatter unable to allow numbers to start with a 0

So I'm attempting to automatically add slashes between 2 digits when a user enters in their birthday, but for some reason when the birthday starts with a 0, the number formatter erases it and messes up the birthday. I've got my code below, could someone help me figure out how to do this? Thanks in advance!
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ;
[formatter setGroupingSeparator:#"/"];
[formatter setGroupingSize:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setSecondaryGroupingSize:2];
NSString *num = textField.text ;
if(![num isEqualToString:#""])
{
num= [num stringByReplacingOccurrencesOfString:#"/" withString:#""];
NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
textField.text=str;
}
What you could do is the following:
Check the length of the string
If length mod 2 == 0 then add "/"
Log your string
I'm not saying this is recommended but it might help you a bit!
- (void)controlTextDidChange:(NSNotification *)obj{
NSString *num = [textField stringValue] ;
if (num.length%2==0)
{
NSString *someText = [NSString stringWithFormat: #"%#/ ", num];
num = someText;
}
textField.stringValue = num;
}
Something like this may help:
NSMutableString *string = #"YOUR TEXTFIELD TEXT";
NSString *lastString = [string substringWithRange:NSMakeRange(string.length-2, 1)];
if ([lastString isEqualToString:#"/"]) {
return;
}
if (string.length == 2 || string.length == 5) {
[string appendString:#"/"];
}

How to round Decimal values in Objective C

This may be a easy question but i am not able to find the logic.
I am getting the values like this
12.010000
12.526000
12.000000
12.500000
If i get the value 12.010000 I have to display 12.01
If i get the value 12.526000 I have to display 12.526
If i get the value 12.000000 I have to display 12
If i get the value 12.500000 I have to display 12.5
Can any one help me out please
Thank You
Try this :
[NSString stringWithFormat:#"%g", 12.010000]
[NSString stringWithFormat:#"%g", 12.526000]
[NSString stringWithFormat:#"%g", 12.000000]
[NSString stringWithFormat:#"%g", 12.500000]
float roundedValue = 45.964;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
NSLog(numberString);
[formatter release];
Some modification you may need-
// You can specify that how many floating digit you want as below
[formatter setMaximumFractionDigits:4];//2];
// You can also round down by changing this line
[formatter setRoundingMode: NSNumberFormatterRoundDown];//NSNumberFormatterRoundUp];
Reference: A query on StackOverFlow
Obviously taskinoor's solution is the best, but you mentioned you couldn't find the logic to solve it... so here's the logic. You basically loop through the characters in reverse order looking for either a non-zero or period character, and then create a substring based on where you find either character.
-(NSString*)chopEndingZeros:(NSString*)string {
NSString* chopped = nil;
NSInteger i;
for (i=[string length]-1; i>=0; i--) {
NSString* a = [string substringWithRange:NSMakeRange(i, 1)];
if ([a isEqualToString:#"."]) {
chopped = [string substringToIndex:i];
break;
} else if (![a isEqualToString:#"0"]) {
chopped = [string substringToIndex:i+1];
break;
}
}
return chopped;
}

How to convert int to NSString?

I'd like to convert an int to a NSString in Objective C.
How can I do this?
Primitives can be converted to objects with #() expression. So the shortest way is to transform int to NSNumber and pick up string representation with stringValue method:
NSString *strValue = [#(myInt) stringValue];
or
NSString *strValue = #(myInt).stringValue;
NSString *string = [NSString stringWithFormat:#"%d", theinteger];
int i = 25;
NSString *myString = [NSString stringWithFormat:#"%d",i];
This is one of many ways.
If this string is for presentation to the end user, you should use NSNumberFormatter. This will add thousands separators, and will honor the localization settings for the user:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:#(n)];
In the US, for example, that would create a string 10,000, but in Germany, that would be 10.000.