我正在开发一款包含收银机的iOS应用程序。我需要能够输入数字并使小数点保持原样就像真正的收银机一样。
目前使用的代码示例是:
-(IBAction)Number1:(id)sender{
SelectNumber = SelectNumber * 10;
SelectNumber = SelectNumber + 1;
Screen.text = [NSString stringWithFormat:@"%i", SelectNumber];
}
例如,您可以从:
开始0.00
然后按1
0.01
然后按2然后按3
1.23
然后是五个
12.35
目前,如果我这样做,我最终将从0.00变为1235(无小数)
我不知道怎么做到这一点,我的谷歌搜索迄今为止都没有让我失望。任何想法/解决方案?
答案 0 :(得分:4)
您可以创建以所需格式显示数字的方法:
-(NSMutableString*)displayNumber:(NSString*)str {
NSMutableString *myNumber = [NSMutableString stringWithFormat:@"%03d", [str intValue]];
[myNumber insertString:@"." atIndex:myNumber.length-2];
return myNumber;
}
您可以创建可变字符串来表示数字,只需附加另一个数字并使用displayNumber方法以您想要的格式显示它:
NSMutableString *number = [NSMutableString stringWithString:@""];
NSLog(@"%@", [self displayNumber:number]); // 0.00
[number appendString:@"2"];
NSLog(@"%@", [self displayNumber:number]); //0.02
[number appendString:@"3"];
NSLog(@"%@", [self displayNumber:number]); //0.23
[number appendString:@"1"];
NSLog(@"%@", [self displayNumber:number]); //23.1
[number appendString:@"5"];
NSLog(@"%@", [self displayNumber:number]); //23.15
您应该处理一些验证,以确保用户只添加数值。
答案 1 :(得分:3)
您可以使用NSDecimalNumber
。
以下是基本要素:
NSDecimalNumber
NSNumberFormatter
// Our properties
@property (nonatomic, strong) NSNumberFormatter *numberFormatter;
@property (nonatomic, strong) NSDecimalNumber *accumulator;
@property (nonatomic, strong) NSMutableString *accumulatorString;
// Initial values
_accumulator = [NSDecimalNumber zero];
_accumulatorString = [NSMutableString stringWithString:@"0"];
_numberFormatter = [[NSNumberFormatter alloc] init];
_numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
_numberFormatter.currencySymbol = @"$";
// You might want to adjust the formatter depending on the locale
// Here is a minimal setup just for the purpose of this example
// The user taps a number
// Of course the digit will be provided dynamically
// (something like [sender currentTitle] for example
// would be ok for a numeric keypad scenario)
[self.accumulatorString appendString:@"6"];
// Update our decimal number
// Here if our string is '06' with mantissa -2 => 0.06
// string '061' with mantissa -2 => 0.61 and so on...
self.accumulator = [NSDecimalNumber decimalNumberWithMantissa:[self.accumulatorString integerValue]
exponent:-2
isNegative:NO];
// Update the display
self.myDisplayLabel.text = [self.numberFormatter stringFromNumber:self.accumulator];