本文介绍了如何更改iOS的小数位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的计算器应用程序,我希望它是如此,如果答案不需要小数位,没有,只有整数。如果答案是2,我不希望它说2.000000,它应该说2.如果它需要一个小数位,它应该显示一个小数位,例如12.8而不是12.80。我该怎么办?这是我的代码。
顺便说一句,这是来自,而不是我自己的工作。

I have a simple calculator app and I want it to be so that if the answer requires no decimal places, there are none, just whole numbers. If the answer was 2, I don't want it to say 2.000000, it should say 2. If it requires one decimal place, it should show to one decimal place for example 12.8 instead of 12.80. How would I do this? Here is my code.btw, this is from a tutorial at http://www.youtube.com/watch?v=Ihw0cfNOrr4, not my own work.

viewcontroller.h

viewcontroller.h

#import <UIKit/UIKit.h>

interface calcViewController : UIViewController {

float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;

}


-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;



@end

in。 m

#import "calcViewController.h"

@implementation calcViewController



-(IBAction)buttonDigitPressed:(id)sender {


currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:@"%2f", currentNumber];

}

-(IBAction)buttonOperationPressed:(id)sender {
if (currentOperation ==0) result = currentNumber;
else {


switch (currentOperation) {
    case 1:
        result = result + currentNumber;
        break;
    case 2:
        result = result - currentNumber;
        break;
    case 3:
        result = result * currentNumber;
        break;
    case 4:
        result = result / currentNumber;
        break;
    case 5:
       currentOperation = 0;
        break;




}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:@"%2f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];

}

-(IBAction)cancelInput {

currentNumber =0;
calculatorScreen.text = @"0";

}


-(IBAction)cancelOperation {



currentNumber = 0;
calculatorScreen.text = @"0";
currentOperation = 0;

}


推荐答案

单向是使用NSNumberFormatter来格式化你的结果而不是NSString的 -stringWithFormat:

One way is to use NSNumberFormatter to format your result instead of NSString's -stringWithFormat::

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:requiredDigits];
[formatter setMinimumFractionDigits:0];
NSString *result = [formatter stringFromNumber:[NSNumber numberWithFloat:currentNumber];

这篇关于如何更改iOS的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 04:35