Nick LaMarca
Nick LaMarca

Reputation: 8188

Converting NSString to a decimal

I need to change the code below to make "intAmount" a decimal or an integer (i.e. a person can enter .10 or 1) in my uitextfield. The last line "myProduct" has to be a decimal not an integer and return the product in the format "18.00" for example. Can someone help someone help me alter my code snippit for this?

//amt has to be converted into a decimal value its a NSString now
NSInteger intAmount = [amt intValue];
//where total gets updated in the code with some whole (integer) value
NSInteger total=0;
//Change myProduct to a decimal with presicion of 2 (i.e. 12.65)
NSInteger myProduct=total*intAmount;

THIS DOESN'T WORK

NSDecimalNumber intAmount = [amt doubleValue];
//Keep in mind totalCost is an NSInteger
NSDecimalNumber total=totalCost*intAmount;

Upvotes: 0

Views: 4947

Answers (3)

dreamlax
dreamlax

Reputation: 95335

If you have a string representation of a real number (non-integer), you can use an NSScanner object to scan it into a double or float, or even an NSDecimal structure if that is your true intention (the NSDecimal struct and NSDecimalNumber class are useful for containing numbers that can be exactly represented in decimal).

NSString *amt = @"1.04";
NSScanner *aScanner = [NSScanner localizedScannerWithString:amt];
double theValue;

if ([aScanner scanDouble:&theValue])
{
    // theValue should equal 1.04 (or thereabouts)
}
else
{
    // the string could not be successfully interpreted
}

The benefit to using a localised NSScanner object is that the number is interpreted based on the user's locale, because “1.000” could mean either one-thousand or just one, depending on your locale.

Upvotes: 0

Lily Ballard
Lily Ballard

Reputation: 185671

If you need to track decimal values explicitly, you can use NSDecimalNumber. However, if all you're doing is this one operation, Carl's solution is most likely adequate.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224944

Use doubleValue instead of intValue to get the correct fractional number out of your text field. Put it in a variable of type double rather than NSInteger. Then use the format %.2g when you print it out and it will look like you want it to.

Upvotes: 3

Related Questions