NSString to NSNumber convert - iphone

I try to convert a string :
3033547640189791162
with this method :
NSNumber * myNumber = [NSNumber numberWithDouble:[tmpId doubleValue]];
and this :
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterNoStyle];
NSNumber * myNumber = [f numberFromString:tmpId];
[f release];
and both of them give me this number :
<CFNumber 0x13a2b0 [0x3f54c9f8]>{value = +3033547640189791232.00000000000000000000, type = kCFNumberFloat64Type}
insted of :
<CFNumber 0x1b5550 [0x3f54c9f8]>{value = +3033547640189791232, type = kCFNumberSInt64Type}
Edit
When i try to use :
NSString *tmpId = #""3033547640189791162";
long i = [tmpId longLongValue];
i is equal to = -1631802438
int i = [tmpId intValue];
i is equal to = 2147483647
so i lose the original number value

If you want your NSNumber to hold an integer value you have to use [NSNumber numberWithInt:]:
NSNumber *myNumber = [NSNumber numberWithInt:[tmpId intValue]];
You should also consider to make sure, that your NSString contains a valid integer value:
NSScanner* scan = [NSScanner scannerWithString:tmpId];
int isInt;
if ( [scan scanInt:&isInt] && isInt ) {
NSLog(#"value is an integer: %i",isInt);
}
But there's a catch:
NSScanner validates the number inside the string as an integer, even though it should not … All ARM processors are 32-bit only, so the maximum range of an unsigned int is 0 to 4294967295.
So using NSNumberFormatter is the safest way to get the right value, because it handles finding the right data type for you:
NSString *tmpId = #"3033547640189791162";
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *myNumber = [f numberFromString:tmpId];

Moving my comment to answer:
Try NSNumber * myNumber = [NSNumber numberWithLongLong:[tmpId longLongValue]];

Related

How to convert currency from string format to number format?

I need to convert currency from string format to number format.
For example my string variable value is #"10 lakh". The string value for this converted into number format would be 1000000. How can one make this type of conversion?
(Converting 10 lakh to 1000000, this is the issue)
Try
- (NSNumber *)multiplierForKey:(NSString *)key
{
NSDictionary *dict = #{#"thousand":#1000, #"lakh":#100000, #"million":#1000000, #"crore":#100000000};
NSNumber *value = dict[[key lowercaseString]];
return value?value:#1;
}
- (void)findMultiplier{
NSString *string = #"10 lakh";
NSArray *components = [string componentsSeparatedByString:#" "];
if ([components count]==2) {
NSNumber *value = components[0];
NSString *key = components[1];
NSNumber *multiplier = [self multiplierForKey:key];
NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithDecimal:[value decimalValue]];
NSDecimalNumber *multiplierValue = [NSDecimalNumber decimalNumberWithDecimal:[multiplier decimalValue]];
NSDecimalNumber *finalValue = [decimalValue decimalNumberByMultiplyingBy:multiplierValue];
NSLog(#"Value : %#",finalValue);
}
}
You can make switch cases according to your denominations. By choosing particular switch case you can choose the desired value. I don't think there is predefined method to accomplish this.
hope this helps.

Checking input value

I am trying to check whether the user gives an input that is number but not letters. When a non-numeric value is given I want to print an alert error message like "incorrect format".
This is my source code:
-(IBAction)btnPressed{
NSString *firstString = textFiled1.text;
NSString *secondString = textFiled2.text;
NSString *thirdString = textFiled3.text;
int num1;
int num2;
int num3;
int output;
num1 = [firstString intValue];
num2 = [secondString intValue];
num3 = [thirdString intValue];
output = (num1 + num2) / num3;
lable1.text = [NSString stringWithFormat:#"%d",output];
}
Use NSNumberFormatter. If the input parameter is not a valid number, the number derived will be nil.
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
num1 = [f numberFromString:firstString];
[f release];
if (num1 == nil) {
// throw exception
}
This is how I would do it:
NSCharacterSet *nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([firstString rangeOfCharacterFromSet:nonNumbers].location != NSNotFound) {
// firstString has non-number characters in it!
}

iPhone NSNumberFormatter for less than 1 value

I have a floating point value
i.e. 0.0467
Want have a string
05
how can get it? Excluding the decimal point (.).
More precisely, if I have a floating point number, I want to divide it to integral and decimal, preferably into two string parts.
By following this, you will get desired result.
float floatValue = 0.0467;
NSString *str = [NSString stringWithFormat:#"%.2f", floatValue];
str = [str stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:#""];
NSLog(#"%#", str); // Result will be: 05
fDecimal = 0.04567;
NSString * strDecimal = [NSString stringWithFormat:#"%0.2f", fDecimal];
NSString * strDecimalPart = [strDecimal substringWithRange:NSMakeRange(2, 2)];
The setting you are looking for is called fraction digits:
NSNumberFormatter* f = [[[NSNumberFormatter alloc] init] autorelease;
[f setMaximumFractionDigits:2];
Optionally you can use -[NSNumberFormatter setRoundingMode:] to specify how rounding should be done.

Correctly convert NSString to NSnumber

I can't figure out why it's not working, I have a NSString which I need to convert to NSNumber (to save it to Core Data)
e.g
NSLog(stringNum);
returns 1
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *myNumber = [f numberFromString:stringNum];
[f release];
NSLog(#"myNumber = %i", myNumber);
returns 120882496 or something like this
What am I missing?
Thanks for help
It's now an object, not an integer, therefore you must use %# in NSLog, not %i.
myNumber is an object, so the format should be
#"myNumber = %#"

NSString stringWithFormat question

I am trying to build a small table using NSString. I cannot seem to format the strings properly.
Here is what I have
[NSString stringWithFormat:#"%8#: %.6f",e,v]
where e is an NSString from somewhere else, and v is a float.
What I want is output something like this:
Grapes: 20.3
Pomegranates: 2.5
Oranges: 15.1
What I get is
Grapes:20.3
Pomegranates:2.5
Oranges:15.1
How can I fix my format to do something like this?
you could try using - stringByPaddingToLength:withString:startingAtIndex:
NSDictionary* fruits = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:20.3], #"Grapes",
[NSNumber numberWithFloat:2.5], #"Pomegranates",
[NSNumber numberWithFloat:15.1], #"Oranges",
nil];
NSUInteger longestNameLength = 0;
for (NSString* key in [fruits allKeys])
{
NSUInteger keyLength = [key length];
if (keyLength > longestNameLength)
{
longestNameLength = keyLength;
}
}
for (NSString* key in [fruits allKeys])
{
NSUInteger keyLength = [key length];
NSNumber* object = [fruits objectForKey:key];
NSUInteger padding = longestNameLength - keyLength + 1;
NSLog(#"%#", [NSString stringWithFormat:#"%#:%*s%5.2f", key, padding, " ", [object floatValue]]);
}
Output:
Oranges: 15.10
Pomegranates: 2.50
Grapes: 20.30
The NSNumberFormatter class is the way to go!
Example:
NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
[numFormatter setPaddingCharacter:#"0"];
[numFormatter setFormatWidth:2];
NSString *paddedString = [numFormatter stringFromNumber:[NSNumber numberWithInteger:integer]];
[numFormatter release];
I think you want something like
[NSString stringWithFormat:#"%-9# %6.1f",[e stringByAppendingString:#":"],v]
since you want padding in front of the float to make it fit the column, though if the NSString is longer than 8, it will break the columns.
%-8f left-aligns the string in a 9-character-wide column (9-wide since the : is appended to the string beforehand, which is done so the : is at the end of the string, not after padding spaces); %6.1f right-aligns the float in a 6-char field with 1 decimal place.
edit: also, if you're viewing the output as if it were HTML (through some sort of web view, for instance), that may be reducing any instances of more than one space to a single space.