嘿,所以我有针对我正在研究的东西的测试程序。

它有什么作用? -它基本上减去了每月应付款总额中的每月贷款额,然后将其插入到数组中,它可以工作,但是我需要将其格式化为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;
}

将不胜感激。

非常感谢您的宝贵时间。

最佳答案

查看 NSDecimalNumber :

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

只是要记住要记住将变量复制到通常分配它们的位置,因为您正在处理对象,而不是此处的基元!

关于objective-c - 在添加到数组之前格式化为小数点后2位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9812723/

10-10 17:36