Re: NSDecimalNumber & NSString question
Re: NSDecimalNumber & NSString question
- Subject: Re: NSDecimalNumber & NSString question
- From: Ashley Clark <email@hidden>
- Date: Wed, 19 Nov 2008 01:36:19 -0600
On Nov 18, 2008, at 4:28 PM, Brooke Gravitt wrote:
Hello,
I'm trying to better acquainted with Cocoa and Obj-C, having some
trouble with simple things. Perhaps someone could kindly apply cluebat
to skull for me.
I'm accepting a couple of string values from a pair of NSTextField and
would like to take these values and do some math with them, then
display them back in a Label.
....
NSString *aString = aField.text;
NSString *bString = bField.text;
NSDecimalNumber *aAmt = [NSDecimalNumber
decimalNumberWithString:aString];
NSDecimalNumber *bAmt = [NSDecimalNumber
decimalNumberWithString:bString];
NSDecimalNumber *myTotal;
NSDecimalNumber *myPct;
NSDecimalNumber *multFactor;
myPct = [bAmt decimalNumberByDividingBy:100]; // divide by 100 to
get % ( 0.XX )
multFactor = [myPct decimalNumberByAdding:1]; // add 1 so we can
multiply by 1.XX
The decimalNumberByMultiplyingBy and decimalNumberByDividingBy methods
both expect their arguments to be NSDecimalNumber objects as well, not
number literals.
If you just want to divide by 100 though, you can call [bAmt
decimalNumberByMultiplyingByPowerOf10:(-2)].
And NSDecimalNumber has class constructors for zero and one, so your
second line would be:
[myPct decimalNumberByAdding:[NSDecimalNumber one]].
newAmt = [bAmt decimalNumberByMultiplyingBy:myPct];
myTotal = [aAmt decimalNumberByAdding:bAmt];
aLabel.text = newAmt;
bLabel.text = myTotal;
Here you'll need to convert your NSDecimalNumber's to NSStrings. You
can either call the description method and use that value if you're
not interested in formatting the number, but I'd suggest you use an
NSNumberFormatter to determine how you want to present the numbers.
[aString release];
....
None of this works, at all. So how to I grab 2 strings from text
fields, extract their numerical value, do some math, then apply them
to labels?
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden