[英]NSNumber/NSString math returns correct value but with a minus sign
code: 码:
-(IBAction)addRounds{
NSString *addText = [NSString stringWithFormat:@"%@", self.roundsF.text];
NSString *totalText = [NSString stringWithFormat:@"%@", self.totalRoundsF.text];
int value = [totalText intValue] - [addText intValue];
NSNumber *val = [NSNumber numberWithInt:value];
NSString *final = [NSString stringWithFormat:@"%@", val.stringValue];
self.totalRoundsF.text = final;
}
The above code works perfectly, however when it displays the data into the textfield, it will show something like : -10
the number 10 is correct, i just dont want a -
sign. 上面的代码可以完美地工作,但是当它在文本字段中显示数据时,它将显示类似:
-10
的数字10是正确的,我只是不想要-
号。 Any help is greatly appreciated, Thank you very much! 非常感谢任何帮助,非常感谢!
You do not want negative value at all? 您根本不想要负值吗? In that case use
abs
absolute value. 在这种情况下,请使用
abs
绝对值。 This will always give you positive values. 这将始终为您带来积极的价值。
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
. 根据变量的类型,
abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
或fabsl(long double)
。
These functions are part of the C library and are present in Objective-C library as well. 这些函数是C库的一部分,并且也存在于Objective-C库中。 You might have to import
math.h
to use them. 您可能需要导入
math.h
才能使用它们。
so in your case it would be abs(val); //will give +10
因此,在您的情况下,它将为
abs(val); //will give +10
abs(val); //will give +10
change NSNumber *val = [NSNumber numberWithInt:value];
更改
NSNumber *val = [NSNumber numberWithInt:value];
this to NSNumber *val = [NSNumber numberWithInt:abs(value)];
这到
NSNumber *val = [NSNumber numberWithInt:abs(value)];
-(IBAction)addRounds{
self.totalRoundsF.text = [NSString stringWithFormat:@"%d", [self.roundsF.text intValue] - [self.totalRoundsF.text intValue]];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.