我正在尝试制作这个程序,以便只有小数是.5
时才有小数。我一直在尝试使用[string substringToIndex:[string length] - 2]
,但它什么也没做。是因为它不能附加浮动?
float inchesInField = [sizeField.text floatValue];
float shoeSize = inchesInField * 3 - 22;
NSMutableString *appendedShoeSize = [[NSMutableString alloc]
initWithFormat:@"%.1f", shoeSize];
if ([appendedShoeSize hasSuffix:@".3"] || [appendedShoeSize hasSuffix:@".5"] ||
[appendedShoeSize hasSuffix:@".4"] || [appendedShoeSize hasSuffix:@".6"])
{
[appendedShoeSize substringToIndex:[appendedShoeSize length] - 2];
[appendedShoeSize appendString:@" ½"];
}
if ([appendedShoeSize hasSuffix:@".0"] || [appendedShoeSize hasSuffix:@".1"] ||
[appendedShoeSize hasSuffix:@".2"])
{
[appendedShoeSize substringToIndex:[appendedShoeSize length] - 2];
}
答案 0 :(得分:3)
这是因为NSString的substringToIndex:方法返回新字符串,它不会修改原始字符串。 appendString:很好,但substringToIndex:是NSString的一个方法,所以它不会编辑原始字符串。
这应该这样做:
float inchesInField = [sizeField.text floatValue];
float shoeSize = inchesInField * 3 - 22;
NSMutableString *appendedShoeSize = [[NSMutableString alloc] initWithFormat:@"%.1f", shoeSize];
if ([appendedShoeSize hasSuffix:@".3"] || [appendedShoeSize hasSuffix:@".5"] || [appendedShoeSize hasSuffix:@".4"] || [appendedShoeSize hasSuffix:@".6"]) {
appendedShoeSize = [[appendedShoeSize substringToIndex:[appendedShoeSize length] - 2] mutableCopy];
[appendedShoeSize appendString:@" ½"];
}
if ([appendedShoeSize hasSuffix:@".0"] || [appendedShoeSize hasSuffix:@".1"] || [appendedShoeSize hasSuffix:@".2"]) {
appendedShoeSize = [[appendedShoeSize substringToIndex:[appendedShoeSize length] - 2] mutableCopy];
}
答案 1 :(得分:0)
当您调用substringToIndex:时,它不会修改现有字符串。它返回一个结果。你必须使用类似的东西: NSString * result = [attachedShoeSize substringToIndex:[attachedShoeSize length] - 2];
答案 2 :(得分:0)
Daniel指出substringToIndex:
会返回一个新字符串。
您应该使用replaceCharactersInRange:withString:
,例如:
NSRange range; range.location = [appendedShoeSize length] - 2; range.length = 2;
[appendedShoeSize replaceCharactersInRange:range withString:@" ½"]
有关NSMutableString方法的更多参考资料可在http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/Reference/Reference.html
找到答案 3 :(得分:0)
这不是一个答案,而是一个替代方案,所有那些hasSuffix:
只是稍微磨一下。我认为这样做你想要的:
float intpart;
float fracpart = modff(shoeSize, &intpart);
NSMutableString *appendedShoeSize;
int size = (int)intpart;
if (fracpart >= 0.3 && fracpart <= 0.6)
appendedShoeSize = [[NSMutableString alloc] initWithFormat:@"%d½", size];
else
{ if (fracpart > 0.6) size += 1;
appendedShoeSize = [[NSMutableString alloc] initWithFormat:@"%d", size];
}
modff
将float分成其小数(返回值)和整数(通过引用参数)部分。这段代码片段不需要一个可变的字符串,但是我把它留在了里面,因为你以后可能正在做其他事情。片段也碰撞.7 - > .9到下一个尺寸。