有人可以確認我這是正確的方法來將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