在简单的计算器应用程序中删除不必要的零

时间:2012-04-01 16:58:26

标签: ios xcode calculator

我制作了一个简单的计算器,每当我点击计算它时,我会给出一个答案,但会给出六个不必要的零,我的问题是,如何删除那些零?

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

3 个答案:

答案 0 :(得分:1)

我想补充一点,如果您使用%g说明符,则不需要这样做。

答案 1 :(得分:0)

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

<强>的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”

之前添加一个点和一个数字来指定要返回的小数位数

-Edited -

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

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

答案 2 :(得分:0)

请试一试。这完全符合您的要求。

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];
}

如果您需要更多帮助,请与我联系。

希望这会对你有所帮助。