双倍完整的整数

时间:2013-10-20 18:13:53

标签: iphone ios objective-c

我正在制作一个iphone计算器应用程序,我遇到了这个问题,我似乎无法找到解决方案。

当用户输入数字时,我将它们转换为double,然后将该双重结果转换为字符串。我使用%g来获得整数。我遇到的问题是大数字显示“E”指数。这是我到目前为止所尝试的

    NSLog(@"Num1: %g", 5000.0*8.0);
    NSLog(@"Num2: %g", 500000.0*85.0);
    NSLog(@"Num3: %f", 500000.0*85.0);
    NSLog(@"Num4: %.4f", 5000.0*8.0);
    NSLog(@"Num5: %.4f", 500000.0*85.0);
    NSLog(@"Num6: %g", 5000000.0/3.7);
    NSLog(@"Num7: %.4f", 5000000.0/3.7); 

这就是我得到的结果

    2013-10-20 14:09:34.261 ECalc[9947:a0b] Num1: 40000
2013-10-20 14:09:34.262 ECalc[9947:a0b] Num2: 4.25e+07
2013-10-20 14:09:34.263 ECalc[9947:a0b] Num3: 42500000.000000
2013-10-20 14:09:34.264 ECalc[9947:a0b] Num4: 40000.0000
2013-10-20 14:09:34.264 ECalc[9947:a0b] Num5: 42500000.0000
2013-10-20 14:09:34.265 ECalc[9947:a0b] Num6: 1.35135e+06
2013-10-20 14:09:34.266 ECalc[9947:a0b] Num7: 1351351.3514

就像普通计算器一样,我希望在数字正常乘以时显示整数。即。

Num2 = 42500000
Num7 = 1351351.3514

所以这是我的问题,是否有一个字符串格式说明符,我可以使用它适合num2和num7结果?我是否需要使用大量逻辑来查看点后的数字是否为零然后截断它们,否则保留它们并使用%.4f?

1 个答案:

答案 0 :(得分:1)

因此,这是一个快速而肮脏的解决方案,可满足您的需求。

double num1 = 5000.0*8.0;
double num7 = 5000000.0/3.7;

int decimalPlaces = 4;

if ((int) num1 == num1)
    NSLog(@"Num1: %0.0f",num1);
else
    NSLog(@"Num1: %0.*f", decimalPlaces, num1);

if ((int) num7 == num7)
    NSLog(@"Num1: %0.0f",num7);
else
    NSLog(@"Num1: %0.*f", decimalPlaces, num7);

但是你似乎还在担心实际上能够拆分NSString。所以,第一个代码块是我推荐的方向。如果您选择在整个计算器中保持复杂并保持在NSString中,那么您可以创建一个将拆分NSString的类,并返回整数或包含所有小数的数字。我在这里给的不仅仅是你需要的,但是因为你是iOS的新手,希望它能帮助你学习,如果你愿意的话,你可以做更多的事情。

-(NSString *)noZeroes:(NSString *)number
{
    int i = 0, decimalPos = 0;

    //NSRange says {startHere, forThisManyCharacters}
    NSRange subRange = {i, 1};
    NSString *substr = [number substringWithRange:subRange];

    while (i<[number length] && !([substr isEqualToString:@"."]))
    {
        i++;
        NSRange subRange = {i, 1};
        substr = [number substringWithRange:subRange];
    }

    //No decimal point in this number
    if (i == [number length])
        return number; //so return the number as is

    decimalPos = i+1;
    NSRange decimalRange = {decimalPos, [number length] - decimalPos};
    NSString *decimals = [number substringWithRange:decimalRange];

    NSRange wholeNumRange = {0, decimalPos};
    NSString *wholeNums =[number substringWithRange:wholeNumRange];

    //Numbers you don't want, you can put anything within a CharacterSet like this
    NSCharacterSet *notZeroes = [NSCharacterSet characterSetWithCharactersInString:@"123456789"];
    NSRange range = [decimals rangeOfCharacterFromSet:notZeroes];
    if (range.location == NSNotFound) {
        // nothing but zeroes in the string
        return wholeNums;

    } else {
        // nonzeroes are present
        return number;
    }
}

您可以使用以下内容来表示:

NSString *Num1 = @"22345.56"
NSString *truncatedNum1 = [self noZeroes:Num1];
NSLog(@"Num1: %@", truncatedNum1);