有人可以确认我这是正确的方法来将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";
您无法使用转换将对象从一个类转换为另一个类。 –
顺便说一句 - 从字符串转换将不会工作,由于领先的'$'。 – rmaddy
另外,请勿使用'stringWithFormat:'将十进制值转换为字符串以显示给用户。相反,使用'NSNumberFormatter'。这将确保该值的格式适合用户的区域设置。而且,不要使用'floatValue'来转换用户输入的数字。再次使用'NSNumberFormatter'将文本解析为'float'。这允许用户以他们的语言环境熟悉的格式输入他们的号码。 – rmaddy