Get a long value from an NSString - objective-c

I need to get a long value from an NSString.
For example, I have this:
NSString *test = #"5437128";
and I need :
long myLong = 5437128;
How I can get this long value from the NSString?
Thank you, it will help me!

long longVariable = [test longLongValue];
See NSString documentation..

Use the NSScanner like in the following code:
unsigned x;
[[NSScanner scannerWithString: s2] scanHexInt: &x];
when typing the scanHexInt stop at scan and see yourself which one you need - there are many possibilities to get values from strings....
You might want to use scanlonglong... having declared your variable as long

use this code :
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
long number = [[numberFormatter numberFromString:string] longValue];
[numberFormatter release];

i use the following in case you don't want to lose the fractions value of your number
double x =[stringValue doubleValue];
instead of
double x = [stringValue longLongValue];
if we assume that we have the following string value
and we want to convert it to double we have 2 ways
NSString * stringValue = #"31.211529225111";
way #1
double x = [stringValue longLongValue];
result will be : x = 31
way #2
double x =[stringValue doubleValue];
result will be : x = 31.211529225111001

Related

NSString intValue deforming actual number

I was making a basic method that takes a Flickr image URL and returns the image's ID.
I'm passing the method the NSString #"http://farm6.staticflickr.com/5183/5629026092_c6762a118f".
The goal is to return the int: 5629026092, which is in the image's URL and is the image's ID.
Here is my method:
-(int)getImageIDFromFlickrURL:(NSString *)imageURL{
NSArray *objectsInURLArray = [imageURL componentsSeparatedByString:#"/"];
NSString *lastObjectInFlickrArray = [objectsInURLArray lastObject];
NSArray *dirtyFlickrIdArray = [lastObjectInFlickrArray componentsSeparatedByString:#"_"];
NSString *flickIDString = [dirtyFlickrIdArray objectAtIndex:0];
NSLog(#"flickr id string: %#",flickIDString);
int flickrID = [flickIDString intValue];
NSLog(#"id: %i",flickrID);
return flickrID;
}
The output in the console is:
2012-05-26 13:30:25.771 TestApp[1744:f803] flickr id string: 5629026092
2012-05-26 13:30:25.773 TestApp[1744:f803] id: 2147483647
Why is calling intValue deforming the actual number?
Use long long instead, your number is greater than int can handle (max being 2147483647 as you can see in your second log)
Your value is too big to represent in 32 bits. The biggest value you can store in a signed 32 bit integer (int) is 2147483647. For unsigned ints, it's 4294967295. You need to convert to a long long integer to represent a number as big as 5629026092.
You'll probably need to create a number formatter for that. I'm no expert on number formatters, and always have to dig out the documentation to figure out how to use them.
I just tried it, and this code works:
NSString *numberString = #"5629026092";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *number = [formatter numberFromString: numberString];
long long value = [number longLongValue];
NSLog(#"%# = %qi", numberString, value);
[formatter release];
You could also convert the string to a C string and use scanf, come to think of it.
Easy ^^: INT_MAX Maximum value for a variable of type int. 2147483647
I found this to be a convenient way to do it:
NSString *flickIDString = [dirtyFlickrIdArray objectAtIndex:0]; // read some huge number into a string
// read into a NSNumber object or a long long variable. you choose
NSNumber *flickIDNumber = flickIDString.longLongValue;
long long flickIDLong = flickIDString.longLongValue;

How i can convert NSString to long value?

I have one value 100023 and I have taken it in NSString.
Now I want to pass this value in my web service which contains long parameter type so how can I convert string value to long.
You can use NSString methods intValue longLongValue.
For a small number like this "100023", this is acceptable with 'longlongvalue'. However, if the number digits have more than >10 in which commonly regard as the use case for long value. Then, you will run in into this problem, such as:
String value "86200054340607012013"
do
#"86200054340607012013" integerValue or intValue
you will produce this in the print statement
2147483647
if you do
#"86200054340607012013" longlongvalue
you will produce this in the print statement
9223372036854775807
This works for me and print out the expected number.
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:#"2394739287439284734723"];
NSLog(#"longlong: %llu", [myNumber longLongValue]);
Use this:
yourLong = [yourString longLongValue];
you can use the doubleValue Method to avoid lose of precision warnings
The answer is :
float floatId = [strID floatValue];
Do this...
long value = [myString longValue]

How to pass string to double from NSMutableArray

In array I do have two values value1="234.3423" value2="12.60348" i need to pass this value to varable double x, double y;
How to do this
Thanks in advance.
First, you need to turn them into the number (which you're giving in C string syntax here) into an NSString:
char *value1 = "234.3423";
NSString *string1 = [NSString stringWithUTF8String:value1];
Then, simply do this:
double x = [string1 doubleValue];
That's it. If the simple number parsing of NSString is not enough for you, you will need to look into NSNumberFormatter.
double x=[[myArrayList objectAtIndext:1] doubleValue];
double y=[[myArrayList objectAtIndext:2] doubleValue];
Hope its works for me :D
If not help me any another easy way.

Rounding numbers in Objective-C

I'm trying to do some number rounding and conversion to a string to enhance the output in an Objective-C program.
I have a float value that I'd like to round to the nearest .5 and then use it to set the text on a label.
For example:
1.4 would be a string of: 1.5
1.2 would be a string of: 1
0.2 would be a string of: 0
I've spent a while looking on Google for an answer but, being a noob with Objective-C, I'm not sure what to search for! So, I'd really appreciate a pointer in the right direction!
Thanks,
Ash
Thanks for the pointers everyone, I've managed to come up with a solution:
float roundedValue = round(2.0f * number) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
[formatter release];
The above works for the test cases I threw at it, but if anyone knows a better way to do this I'd be interested to hear it!
float floatVal = 1.23456;
Rounding
int roundedVal = lroundf(floatVal);
NSLog(#"%d",roundedVal);
Rounding Up
int roundedUpVal = ceil(floatVal);
NSLog(#"%d",roundedUpVal);
Rounding Down
int roundedDownVal = floor(floatVal);
NSLog(#"%d",roundedDownVal);
NSString *numberString = [NSString stringWithFormat:#"%f", round(2.0f * number) / 2.0f];
Use lroundf() to round a float to integer and then convert the integer to a string.
NSString *numberString = [NSString stringWithFormat:#"%d",lroundf(number)];
I'd recommend looking into using NSNumberFormatter.
a simple way:
float theFloat = 1.23456;
int rounded = roundf(theFloat); NSLog(#"%d",rounded);
int roundedUp = ceil(theFloat); NSLog(#"%d",roundedUp);
int roundedDown = floor(theFloat); NSLog(#"%d",roundedDown);
// Note: int can be replaced by float
NSString *intNumberString = [NSString stringWithFormat:#"%d", (int)floatNumber];
Following Technique worked for me in a financial application.
NSString *dd=[NSString stringWithFormat:#"%0.2f",monthlyPaymentCalculated];
monthlyPaymentCalculated=[dd doubleValue];
self.monthlyPaymentCritical=monthlyPaymentCalculated;
what is did is first is rounded it with %0.2f and stored it in NSString then i simply converted it again into double and result was good for my calculation.
With these functions you can round to any value.. If you use p=2, you get even numbers.
float RoundTo(float x, float p)
{
float y = 1/p;
return int((x+(1/(y+y)))*y)/y;
}
float RoundUp(float x, float p)
{
float y = 1/p;
return int((x+(1/y))*y)/y;
}
float RoundDown(float x, float p)
{
float y = 1/p;
return int(x*y)/y;
}
I needed to be able to round to a specific digit (not necessarily to whole integers). I made a NSNumber category (based off Ash's answer) and added the following method to it:
- (NSString *)stringByRounding:(NSNumberFormatterRoundingMode)roundingMode
toPositionRightOfDecimal:(NSUInteger)position
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:position];
[formatter setRoundingMode:roundingMode];
NSString *numberString = [formatter stringFromNumber:self];
return numberString;
}
Which allows me to use it like so:
[aNumber stringByRounding:NSNumberFormatterRoundUp toPositionRightOfDecimal:2];
I can use it to round to integers by passing in 0 as the second parameter:
[aNumber stringByRounding:NSNumberFormatterRoundPlain toPositionRightOfDecimal:0];

How to convert a string into double and vice versa?

I want to convert a string into a double and after doing some math on it, convert it back to a string.
How do I do this in Objective-C?
Is there a way to round a double to the nearest integer too?
You can convert an NSString into a double with
double myDouble = [myString doubleValue];
Rounding to the nearest int can then be done as
int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))
I'm honestly not sure if there's a more streamlined way to convert back into a string than
NSString* myNewString = [NSString stringWithFormat:#"%d", myInt];
To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.
Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.
It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.
Adding to olliej's answer, you can convert from an int back to a string with NSNumber's stringValue:
[[NSNumber numberWithInt:myInt] stringValue]
stringValue on an NSNumber invokes descriptionWithLocale:nil, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:#"%d",myInt] will give you a properly localized reprsentation of myInt.
Here's a working sample of NSNumberFormatter reading localized number String (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)
NSString *tempStr = #"8,765.4";
// localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
// next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial
NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(#"string '%#' gives NSNumber '%#' with intValue '%i'",
tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release]; // good citizen
olliej's rounding method is wrong for negative numbers
2.4 rounded is 2 (olliej's method gets this right)
−2.4 rounded is −2 (olliej's method returns -1)
Here's an alternative
int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))
You could of course use a rounding function from math.h
// Converting String in to Double
double doubleValue = [yourString doubleValue];
// Converting Double in to String
NSString *yourString = [NSString stringWithFormat:#"%.20f", doubleValue];
// .20f takes the value up to 20 position after decimal
// Converting double to int
int intValue = (int) doubleValue;
or
int intValue = [yourString intValue];
For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.
int myInt = (int)round( [#"1.6" floatValue] );
NSString* myString = [#(myInt) description];
(Boxes it up as a NSNumber and converts to a string using the NSObjects' description method)
For rounding, you should probably use the C functions defined in math.h.
int roundedX = round(x);
Hold down Option and double click on round in Xcode and it will show you the man page with various functions for rounding different types.
This is the easiest way I know of:
float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;
from this example here, you can see the the conversions both ways:
NSString *str=#"5678901234567890";
long long verylong;
NSRange range;
range.length = 15;
range.location = 0;
[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];
NSLog(#"long long value %lld",verylong);
convert text entered in textfield to integer
double mydouble=[_myTextfield.text doubleValue];
rounding to the nearest double
mydouble=(round(mydouble));
rounding to the nearest int(considering only positive values)
int myint=(int)(mydouble);
converting from double to string
myLabel.text=[NSString stringWithFormat:#"%f",mydouble];
or
NSString *mystring=[NSString stringWithFormat:#"%f",mydouble];
converting from int to string
myLabel.text=[NSString stringWithFormat:#"%d",myint];
or
NSString *mystring=[NSString stringWithFormat:#"%f",mydouble];
I ended up using this handy macro:
#define STRING(value) [#(value) stringValue]