I am new to Objective C and iPhone development.
I'm working with a basic calculator. I want to add a large value in text field. How can I display large values like this : 6.67543 x 10^ -34 in Xcode?
Thank you
You could set up a NSNumberFormatter with NSNumberFormatterScientificStyle and call stringFromNumber... However, the issue I think is going to be with the precision you are hoping to support requires a specialized framework. There might be one based on GNU MP Bignum library out there, but I don't know it off hand.
Use Double data type. And then convert it into string then pass that string to your textField.
For eg:-
double result;
NSString *strResult = [[NSNumber numberWithDouble:result] stringValue];
It will give you exponential string.
And instead of a UILabel use UITextField.
Related
I was using a Get and Set to store a Double into Core Data as an NSNumber. During this conversion which was something like this.
var number {
get {
return coreDataNumber.double
}
set {
coreDataNumber = NSNumber(double: newValue!)
}
}
If the syntax is wrong, that has nothing to do with my question, I'm just not on my Mac right now. I eventually came to the conclusion the only way to maintain accuracy on the conversion was to use a String to store the Double. I am fine with using this method, but for my future knowledge, is there a way to prevent a number like 0.003459 from becoming 0.0034589999999999999999 when you retrieve it? This wasn't the only conversion error I found. Sometimes it would round when I didn't want it to. I understand this probably has something to do with that not all decimal values can be properly portrayed in binary. If there is a way to convert without losing accuracy I would appreciate that knowledge.
The accuracy is much higher than 6 decimal digits.
Using your numbers:
0.003459 - 0.0034589999999999999999 = 1e-22
The problem is the formatting function (or lack thereof).
I am new to coding and objective C so thanks for the help in advance.
I have a .plist file containing an array of strings filled with formulas such as
*5.3
/2
-10.5
I am able to retrieve these string values from the .plist file but I am getting a little stuck trying to append these string formulas to existing variables with the hopes of returning a converted number. For example I would like to use my variable 7 with the formula *5.3 and return 37.1
7 *5.3 -> 37.1
Any help would be greatly appreciated
Appending the string to a variable is straightforward; it can be accomplished with something like this:
NSString *equation = [NSString stringWithFormat:#"%d%#", variable, plistEntry];
You'll run into problems when you want to evaluate this equation, however. This SO question discusses expression evaluation in Objective-C. Dave DeLong's answer links to a couple of libraries that you may want to look into: DDMathParser and GCMathParser.
This can't be done as-is. You'll need one of the many free expression evaluators (probably in C) that float around on the web.
See this SO question.
I am struggling with very simple thing:
I receive some ids by http request as a string. I know they represent 64-bit integer id numbers.
How can I convert them to the 64-bit Integers (NSNumber or NSInteger)?
Functions like:
[nsstring integerValue],
[nsstring intValue]
seems to be 32bit limited (max value:2147483647).
Any Hints?
Data model with 64bit integer properties compiles fine so it means iPhone supports such a numbers for a god sake.
It must be some simple conversion method. It is so popular in http connection based devices.
have you tried longLongValue ?
if they have a fixed length, you could cut them on each 9th number, make the intvalue of the cutted parts and add the values with the 10^9-factor. surely not the most elegant way, but it should work
I wanted to know if theres a single method or way that will help me replace strings for specific characters.
like MALE - M
FEMALE - F
CHILD - P
The longer way out is this..
[str stringByreplacingOccurencesOfString:#"MALE" withString:#"M"];
[str stringByreplacingOccurencesOfString:#"FEMALE" withString:#"F"];
[str stringByreplacingOccurencesOfString:#"CHILD" withString:#"P"];
I was wondering if theres another way in which i can reduce lines of code here, specially when there are alots of things to replace.
thanks.
this is for iPhone OS.
No, but it shouldn't take more than 5-10 minutes to write a method that takes an array or varargs to do it for you.
I've read a lot about NSDecimal, NSNumber, NSNumberDecimal, CFNumber... and it begins to be a kind of jungle to me.
Basically, I'm trying to create a simple model class that will handle simple computations, like this one:
#import <Foundation/Foundation.h>
#interface Test : NSObject
{
float rate;
float amount;
int duration;
}
- (float)capitalizedAmount;
#end
#implementation Test
- (float)capitalizedAmount {
return (amount*pow((1.0+rate),duration));
}
#end
I want to access these methods and setters with their names as strings, since I plan to have a lot of other classes like this one, and I am only keeping a list of field to do key value coding.
// This is just the desired behavior
// This evidently won't work with the previous class definition
Test *obj = [[Test alloc] init];
[NSNumber numberWithInt:10]
...
float r;
r = [obj performSelector:NSSelectorFromString(#"capitalizedAmount")];
I understand that this is not possible, that performSelector: will return an object, and thus that capitalizedAmount should return an object. I've read things about NSInvocation and the relevant part in the Objective-C Faq on comp.lang.
I also understand that I should use NSDecimalNumber, but there is two things that I would like to know:
Are the memory overhead and performance loss acceptable for a somewhat more complicated class (only financial computations of this kind, showed in an UITableView)? I do not have much background in C...
Isn't it too fastidious and complicated to use functions like decimalNumberByAdding:? With Python it was easy to define __add__ to use operators with objects. Should I get float values from NSDecimalNumber, then do the computations and returns the result wrapped in an NSDecimalNumber? How would you deal with this problem?
I am looking for a simple and beautiful solution!
Just another question in the same area: is CFBoolean the object wrapper for BOOL on iPhone Core Foundation?
Thank you very much for your help!
If you are dealing with financial computations, you really should use base-10 arithmetic to avoid the rounding errors that can occur with the standard base-2 floating point types. So it's either NSDecimal or NSDecimalNumber. And since you're writing object-oriented code, NSDecimalNumber is the right choice for you.
To answer your questions: only testing of your code can reveal whether the memory overhead and performance loss are acceptable to you. I haven't really worked much with NSDecimalNumber but I'd wager that Apple's implementation is quite efficient and will be more than adequate for most people's needs.
Unfortunately, you won't be able to avoid the likes of decimalNumberByAdding: since Objective-C does not support operator overloading like C++ does. I agree that it makes your code somewhat less elegant.
One comment on the code you posted: r = [obj performSelector:NSSelectorFromString(#"capitalizedAmount")]; is rather unelegant. Either
r = [obj performSelector:#selector(capitalizedAmount)];
or even the simple
r = [obj capitalizedAmount];
would be better unless you require the NSSelectorFromString syntax for some other reason.
Ole is correct, in that you should be using NSDecimal or NSDecimalNumber to avoid floating point math errors when doing financial calculations. However, my suggestion would be to use NSDecimal and its C functions, rather than NSDecimalNumber. NSDecimal calculations can be much faster, and since they avoid creating a lot of autoreleased objects, much better on memory usage.
As an example, I benchmarked math operations for the two types on my MacBook Air:
NSDecimal
Additions per second: 3355476.75
Subtractions per second: 3866671.27
Multiplications per second: 3458770.51
Divisions per second: 276242.32
NSDecimalNumber
Additions per second: 676901.32
Subtractions per second: 671474.6
Multiplications per second: 720310.63
Divisions per second: 190249.33
Divisions were the only operation that didn't experience a roughly fivefold increase in performance when using NSDecimal vs. NSDecimalNumber. Similar performance improvements occur on the iPhone. This, along with the memory savings, were why we recently switched Core Plot over to using NSDecimal.
The only difficulty you'll run into is in getting values into and out of the NSDecimal types. Going directly to and from float and integer values might require using NSDecimalNumber as a bridge. Also, if you use Core Data, you'll be storing your values as NSDecimalNumbers, not NSDecimals.
I want to access these methods and setters with their names as strings, since I plan to have a lot of other classes like this one, and I am only keeping a list of field to do key value coding.
r = [obj performSelector:NSSelectorFromString(#"capitalizedAmount")];
KVC is not simply sending messages to objects using strings. See the Key-Value Coding Programming Guide.
Should I get float values from NSDecimalNumber, then do the computations and returns the result wrapped in an NSDecimalNumber?
No. Conversion to binary floating-point (float/double) from decimal floating-point (NSDecimal/NSDecimalNumber) is lossy. Your result will be incorrect for some calculations if you do them that way.