I would like to add, if you don't use something to validate the user input of your text fields you, will crash with non numeric characters.

Steven Riggs

On Nov 19, 2008, at 2:36 AM, Ashley Clark <[EMAIL PROTECTED]> wrote:

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 (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/steven.riggs%40me.com

This email sent to [EMAIL PROTECTED]
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to