How to pass string to double from NSMutableArray - objective-c

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.

Related

How do I convert a decimal to hexadecimal using Objective C?

I've been working on a calculator and I wanted to implement conversions from decimal to octal and from decimal to hexadecimal. I'm new to Xcode and Objective C, but I've managed to get a conversion from decimal to octal, it just doesn't seem to work with hexadecimal.
Here's the code I've written to convert a double to octal:
double result = 0;
...
double decToOct = [self popOperand];
NSString *oct = [NSString stringWithFormat:#"%llo", (long long)decToOct];
result = [oct doubleValue];
Using the same scheme (obviously that includes changing #"%llo" with #"%llx") the conversion to hexadecimal works up to a certain point. It does numbers 0 through 9 just fine, but once it hits 10, it comes up as 0. To test, I also input 5395 and it displayed 1513, the desired result.
Because of this, I can only assume that for some reason my code does not want to input the actual letters of the hexadecimal values (e.g. 11 would convert to B but it shows up as 0) .
Any suggestions? Thanks in advance.
UPDATE:
In addition, I have also been using this to display the result:
double result = [self.brain performOperation:operation];
self.display.text = [NSString stringWithFormat:#"%g", result];
result, as listed from the top, is an argument which is eventually returned here, to self.brain performOperation:operation. This is supposed to handle the display of all operations, including: addition, multiplication, etc. but also octal and hexadecimal. Again, it works fine with octal, but not with hexadecimal.
Try this, May be it will help you. Please do let me know if i am wrong here:--->
NSString *decStr = #"11";
NSString *hexStr = [NSString stringWithFormat:#"%lX",
(unsigned long)[dec integerValue]];
NSLog(#"%#", hexStr);
If you know your string only contains a valid decimal number then the simplest way would be:
NSString *dec = #"254";
NSString *hex = [NSString stringWithFormat:#"0x%lX",
(unsigned long)[dec integerValue]];
NSLog(#"%#", hex);

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

NSString not loading double value

I'm not sure what's going on here. For some reason NSString seems unwilling to load in the double value d.
Here's my code:
-(NSString*)minuteFormat:(double) d{
NSString* mystring;
if(d >= 10){
mystring = [NSString stringWithFormat:#"%d", d];
}else{
mystring = [NSString stringWithFormat:#"0%d",d];
}
return(mystring);
}
Regardless of the value of d, the only thing that's getting returned is 0 or 00. (And I'm sure d is getting inputted correctly, as I've used breakpoints to check.)
Could someone tell me what's going on?
%d is for integers. You probably want %f. See String Format Specifiers
%d is a decimal integer format string. Try %lf for double.
You should use %f (double) like this
mystring = [NSString stringWithFormat:#"%f", f];
or do a typecast of the value. For this you may use [yourString floatValue]

Convert "1.0E-4" from NSString to double

I want to get the double value from "1.04E-4" NSString, but I didn't manage yet how to do it.
I tried the following:
1.
NSString* str = #"1.0E-4";
double value = [str doubleValue]; //returns 0.0001
2.
NSString* str = #"1.0E-4";
double value;
NSScanner* scanner = [NSScanner scannerWithString:str];
[scanner scanDouble:&value];
//0.0001 again
Instead of value = 1.0E-4, I get 0.0001
Could someone help me with this?
Appreciate,
Alex.
For the record, 1.0E-4 = 0.0001.
In Java, if I use Double.parseDouble("1.0E-4") I get 1.0E-4, but in objc I don't know how to do this.I encounter some problems translating some Java code into objc, and this is one of the differences that I've spot since now.

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]