How i can convert NSString to long value? - objective-c

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]

Related

Converting NSString to NSNumber results in too many digits and strange rounding

When converting an NSString, which contains standard decimal numbers with two digits (e.g. 8.20) to a NSNumber, I get (from time to time) extra digits and a strange rounding behavior when logging the result via NSLog or saving it in Core Data (as float or double), e.g. 8.20 -> 8.199999999999999.
This is the code I am using to convert the numbers:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:5];
NSNumber *num = [numberFormatter numberFromString:str];
I do not understand why the conversion to NSNumber messes the number up. What is wrong with my code?
This is just how float and double behaves in C/Objective-C (and many other languages). For example, when you type into python 8.0, the result would be 8.000000000001. I recommend using NSScanner to convert them into primitive number types (double, float).
Why would you use NSNumberFormatter to convert string to float, it would be an overkill,
To convert it just use
NSNumber *num = [NSNumber numberWithFloat:[str floatValue]];
I have encounter the problem when I use NSNumber to save the doublevalue
of 8.28 always show the 8.2799999999...,I guess it cause by a computer numerical precision
Try this code.
+ (NSString *)dealWithDouble:(double)doubleValue {
double d2 = doubleValue;
NSString *d2Str = [NSString stringWithFormat:#"%lf", d2];
NSDecimalNumber *num = [NSDecimalNumber decimalNumberWithString:d2Str];
NSString *str2D = [num stringValue];
return str2D;
}
Don't use floatValue. floatValue only gives 24 bit of precision. doubleValue gives 53 bits of precision. If you use numbers over a million dollars for example, floatValue cannot give you any values that are closer than six cent apart. ($1,000,000 followed by $1,000,000.06 etc. )
The rule is: Don't use float unless you know a reason why you should use float and not double.

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;

parsing string into different kind of number string

I have a string called realEstateWorth with a value of $12,000,000.
I need this same string to remain a string but for any number (such as the one above) to be displayed as $12 MILLION or $6 MILLION. The point is it needs the words "MILLION" to come after the number.
I know there is nsNumberFormatter that can convert strings into numbers and vice versa but can it do what I need?
If anyone has any ideas or suggestions, it would be much appreciated.
Thank you!
So as I see it, you have two problems:
You have a string representation of something that's actually a number
You (potentially) have a number that you want formatted as a string
So, problem #1:
To convert a string into a number, you use an NSNumberFormatter. You've got a pretty simple case:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *n = [f numberFromString:#"$12,000,000"];
// n is 12000000
That was easy! Now problem #2:
This is trickier, because you want a mixed spell-out style. You could consider using an NSNumberFormatter again, but it's not quite right:
[f setNumberStyle:NSNumberFormatterSpellOutStyle];
NSString *s = [f stringFromNumber:n];
// s is "twelve million"
So, we're closer. At this point, you could perhaps maybe do something like:
NSInteger numberOfMillions = [n integerValue] / 1000000;
if (numberOfMillions > 0) {
NSNumber *millions = [NSNumber numberWithInteger:numberOfMillions];
NSString *numberOfMillionsString = [f stringFromNumber:millions]; // "twelve"
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *formattedMillions = [f stringFromNumber:millions]; // "$12.00"
if ([s hasPrefix:numberOfMillionsString]) {
// replace "twelve" with "$12.00"
s = [s stringByReplacingCharactersInRange:NSMakeRange(0, [numberOfMillionsString length]) withString:formattedMillions];
// if this all works, s should be "$12.00 million"
// you can use the -setMaximumFractionDigits: method on NSNumberFormatter to fiddle with the ".00" bit
}
}
However
I don't know how well this would work in anything other than english. CAVEAT IMPLEMENTOR
Worst case scenario, you could implement a category on NSString to implement the behaviour you want.
In the method that you would do in that category you could take an NSNumberFormatter to bring that string to a number and by doing some modulo operation you could define if you need the word Million, or Billion, etc. and put back a string with the modulo for Million or other way you need it to be.
That way you could just call that method on your NSString like this :
NSString *humanReadable = [realEstateWorth myCustomMethodFromMyCategory];
And also.
NSString are immutable, so you can't change it unless you assign a new one to your variable.
I'd recommend storing this value as an NSNumber or a float. Then you could have a method to generate an NSString to display it like:
- (NSString*)numberToCurrencyString:(float)num
{
NSString *postfix = #"";
if (num > 1000000000)
{
num = num / 1000000000;
postfix = #" Billion";
}
else if (num > 1000000)
{
num = num / 1000000;
postfix = #" Million";
}
NSString *currencyString = [NSString stringWithFormat:#"%.0f%#", num, postfix];
return currencyString;
}
Note: Your question states that your input needs to remain a string. That's fine. So you'd need to 1.) first parse the number out of the string and 2.) then reconvert it to a string from a number. I've shown how to do step 2 of this process.

Get a long value from an NSString

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

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]