我从int
UITextField
获取[self.dbRef.text intValue];
值
然后,我想格式化该值,以便可以在数字之前加上小数位。如果[self.dbRef.text intValue];
返回4
,则我需要将该值设为0.04
到目前为止,我已经尝试了多种方法,包括
float Y = ([self.dbRef.text intValue]/100);
slice.value = Y;
NSLog(@"float Y value = %f",Y);
返回零
NSString* formatedTotalApplianceString = [NSString stringWithFormat:@"0.%@", self.dbRef.text];
NSLog(@"formated string = %@",formatedTotalApplianceString);
int totalAppliances = [formatedTotalApplianceString intValue];
NSLog(@"Resulting int value = %d",[formatedTotalApplianceString intValue]);
slice.value = totalAppliances;
NSLog(@"total appliances int value = %d",totalAppliances);
返回零
最佳答案
您正在执行整数除法,因此0
值在那种情况下是正确的,因为整数不能表示分数(除非您正在执行定点算术,但这是蠕虫的另一种形式)。您需要进行浮点除法,例如:
float Y = ([self.dbRef.text floatValue]/100.0f);
[self.dbRef.text floatValue]
或100.0f
都会将其转换为float分隔,因为如果另一端是int
,它将自动转换为float。但是“最佳”方法是使两个值具有相同的类型。
关于ios - 格式化整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954208/