嘿,所以我有一些我正在研究的测试程序。
它做什么? - 它基本上从应付总金额中扣除每月贷款支付,然后将其插入数组,它正在工作但我需要将其格式化为2位小数,我不知道该怎么做,我尝试过使用我找到的方法是
[NSString stringWithFormat: @"%.2lf", tempPaymentHolder]
但它似乎不起作用,这是代码。
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
@autoreleasepool {
//array that would hold the payments
NSMutableArray * arrayWithPayments = [[NSMutableArray alloc]init];
//total amount to be paid
NSMutableString * totalPaymentString = [[NSMutableString alloc]initWithString:@"151.92"];
//monthly payment
NSMutableString * monthlyPaymentsString = [[NSMutableString alloc]initWithString:@"12.66"];
//temp storage for passing values into array
NSMutableString * tempPaymentStringHolder = [[NSMutableString alloc]init];
tempPaymentStringHolder = [NSString stringWithFormat:@"%@",totalPaymentString];
//doubles so I can calculate
int numberOfMonths = 12;
double monthlyPayments = [monthlyPaymentsString doubleValue];
double totalPayment = [totalPaymentString doubleValue];
double tempPaymentHolder = totalPayment;
for (int i = 0; i <= numberOfMonths; i++)
{
[arrayWithPayments addObject:tempPaymentStringHolder];
tempPaymentHolder = totalPayment - monthlyPayments;
totalPayment = tempPaymentHolder;
tempPaymentStringHolder = [NSString stringWithFormat: @"%.2lf", tempPaymentHolder];
}
for (id obj in arrayWithPayments)
{
NSLog(@"%@",obj);
}
}
return 0;
}
感谢任何帮助。
非常感谢你的时间。
答案 0 :(得分:4)
NSMutableArray *arrayOfPayments = [[NSMutableArray alloc]init];
//total amount to be paid
NSDecimalNumber * totalPayment = [NSDecimalNumber decimalNumberWithString:@"151.92"];
//monthly payment
NSDecimalNumber * monthlyPayments = [NSDecimalNumber decimalNumberWithString:@"12.66"];
//temp storage for passing values into array
NSDecimalNumber* tempPaymentHolder = [totalPayment copy];
//variables so I can calculate
int numberOfMonths = 12;
for (int i = 0; i <= numberOfMonths; i++)
{
[arrayOfPayments addObject:tempPaymentHolder];
tempPaymentHolder = [totalPayment decimalNumberBySubtracting:monthlyPayments];
totalPayment = [tempPaymentHolder copy];
}
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
for (NSDecimalNumber *obj in arrayOfPayments)
{
NSLog(@"%@", [formatter stringFromNumber:obj]);
}
输出:
$ 151.92
$ 139.26
$ 126.60
$ 113.94
$ 101.28
$ 88.62
$ 75.96
$ 63.30
$ 50.64
$ 37.98
$ 25.32
$ 12.66
$ 0.00包装
请务必记住将变量复制到通常分配它们的位置,因为您在处理对象而不是原语!