【问题标题】:Removing unnecessary zeros in a simple calculator app在简单的计算器应用程序中删除不必要的零
【发布时间】:2012-04-01 16:58:25
【问题描述】:

我做了一个简单的计算器,每次我点击计算它都会给出一个答案,但给出了六个不必要的零,我的问题,我怎样才能删除这些零?

NSString *firstString = textfieldone.text;
NSString *secondString = textfieldtwo.text;

NSString *LEGAL = @"0123456789";
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:LEGAL] invertedSet];
NSString *filteredOne = [[firstString componentsSeparatedByCharactersInSet:characterSet] 
                         componentsJoinedByString:@""];
NSString *filteredTwo = [[secondString componentsSeparatedByCharactersInSet:characterSet] 
                         componentsJoinedByString:@""];
firstString = filteredOne;
secondString = filteredTwo;

//Here we are creating three doubles
double num1;
double num2;
double output;
//Here we are assigning the values 
num1 = [firstString doubleValue];
num2 = [secondString doubleValue];

output = num1 + num2;

label.text = [NSString stringWithFormat:@"%f",output];

例子:

15 + 15 = 30.000000

【问题讨论】:

  • 使用 NSDecimalNumber,它没有那些精度错误。

标签: ios xcode calculator


【解决方案1】:

我想补充一点,如果您使用 %g 说明符,这些都不是必需的。

【讨论】:

    【解决方案2】:

    如果您使用字符串显示此内容,请检查以下方法。

    NSString

    NSString * display = [NSString stringWithFormat:@"%f", number];
    //This approach will return 30.0000000
    
    NSString * display = [NSString stringWithFormat:@"%.2f", number];
    //While this approach will return 30.00
    

    注意: 您可以通过在'f'之前添加一个点和一个数字来指定要返回的小数位数

    -已编辑-

    在您的情况下,请使用以下方法:

    label.text = [NSString stringWithFormat:@"%.0f", output];
    //This will display your result with 0 decimal places, thus giving you '30'
    

    【讨论】:

      【解决方案3】:

      请试试这个。这应该完全符合您的要求。

      NSString * String1 = [NSString stringWithFormat:@"%f",output];
      NSArray *arrayString = [String1 componentsSeperatedByString:@"."];
      
      float decimalpart = 0.0f;
      if([arrayString  count]>1)
      {
         decimalpart =  [[arrayString objectAtIndex:1] floatValue];
      }
      
      //This will check if the decimal part is 00 like in case of 30.0000, only in that case it would strip values after decimal point. So output will be 30
      if(decimalpart == 0.0f)
      {
         label.text = [NSString stringWithFormat:@"%.0f", output];
      }
      else if(decimalpart > 0.0f) //This will check if the decimal part is 00 like in case of 30.123456, only in that case it would shows values upto 2 digits after decimal point. So output will be 30.12
      {
         label.text = [NSString stringWithFormat:@"%.02f",output];
      }
      

      如果您需要更多帮助,请告诉我。

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-14
        • 1970-01-01
        • 2013-11-29
        相关资源
        最近更新 更多