开发者

Converting NSString to a decimal

开发者 https://www.devze.com 2023-01-06 20:12 出处:网络
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 r

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;


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消