2014-02-18 51 views
1

有人可以确认我这是正确的方法来将NSString转换为NSDecimalNumber?我有一个标签,当你点击这个按钮时,价格出现,这叫做totalPriceCalculated,然后我也有所有的字符串进行计算。提前致谢!字符串NSDecimalNumber不工作

- (IBAction)calculateTotalPrice:(id)sender { 
    NSString *priceStringOne = [hiddenPriceOneTF text]; 
    float priceFloatOne = [priceStringOne NSNumberFormatter]; 

    NSString *priceStringTwo = [hiddenPriceTwoTF text]; 
    float priceFloatTwo = [priceStringTwo floatValue]; 

    NSString *priceStringThree = [hiddenPriceThreeTF text]; 
    float priceFloatThree = [priceStringThree floatValue]; 

    NSString *priceStringFour = [hiddenPriceFourTF text]; 
    float priceFloatFour = [priceStringFour floatValue]; 

    NSString *quanityStringOne = [quanityFirstTF text]; 
    float quanityFloatOne = [quanityStringOne floatValue]; 

    NSString *quanityStringTwo = [quanitySecondTF text]; 
    float quanityFloatTwo = [quanityStringTwo floatValue]; 

    NSString *quanityStringThree = [quanityThirdTF text]; 
    float quanityFloatThree = [quanityStringThree floatValue]; 

    NSString *quanityStringFour = [quanityFourthTF text]; 
    float quanityFloatFour = [quanityStringFour floatValue]; 

    float totalAmount = priceFloatOne * quanityFloatOne + priceFloatTwo * quanityFloatTwo + priceFloatThree * quanityFloatThree + priceFloatFour * quanityFloatFour ; 
    NSString *result = [NSString stringWithFormat:@" $ %0.2f", totalAmount]; 

    [totalPriceCalculated setText:result]; 

    NSString *totalPrice = totalPriceCalculated.text; 
    NSDecimalNumber *totalPriceNumber = (NSDecimalNumber *)totalPrice; 
} 

NSString *priceStringOne = [hiddenPriceOneTF text]; 

float priceFloatOne = [priceStringOne NSNumberFormatter]; 

修订 *

PayPalPayment *payment = [[PayPalPayment alloc] init]; 
payment.amount = [NSDecimalNumber decimalNumberWithString:totalPriceNumber]; 
payment.currencyCode = @"USD"; 
payment.shortDescription = @"Hipster t-shirt"; 
+2

您无法使用转换将对象从一个类转换为另一个类。 –

+0

顺便说一句 - 从字符串转换将不会工作,由于领先的'$'。 – rmaddy

+0

另外,请勿使用'stringWithFormat:'将十进制值转换为字符串以显示给用户。相反,使用'NSNumberFormatter'。这将确保该值的格式适合用户的区域设置。而且,不要使用'floatValue'来转换用户输入的数字。再次使用'NSNumberFormatter'将文本解析为'float'。这允许用户以他们的语言环境熟悉的格式输入他们的号码。 – rmaddy

回答

0

另一种选择是创建从float十进制数:

NSDecimalNumber *totalPriceNumber = [NSDecimalNumber decimalNumberWithDecimal:[@(totalAmount) decimalValue]]; 
+0

我试过这种方式,但是当我将totalPriceNumber添加到我希望插入值的位置时,它仍然给我一个错误,指出将NSDecimalNumber发送到NSString类型的参数的不兼容指针类型。我更新了上面的代码以显示我想要放置totalPriceNumber的位置。 (将其转换为PayPal iOS代码) – bgeorge11

+0

看看你正在尝试做什么。 'totalPriceNumber'已经是一个'NSDecimalNumber',你把它当作'NSString'来处理,并且不必要的尝试创建另一个'NSDecimalNumber'。只要做到:'payment.amount = totalPriceNumber;'。 – rmaddy

+0

真棒谢谢!我刚开始学习iOS编码,所以我对NSDecimalNumber一无所知。所以我会去做一些关于NSNumberFormater的搜索。谢谢 – bgeorge11

0

尝试:

totalPriceNumber = [[NSDecimalNumber alloc] initWithFloat:totalAmount];

+0

由于'totalPrice'中的''''这不起作用。 – rmaddy

+0

确实。已更新为从float读取。 – Guilherme