문제

This may be simple answer... What is the quickest algorithm to check if a number contains more than four digits? I am trying to create an if-then statement. If number x contains more than 4 digits, then...

도움이 되었습니까?

해결책

So, I'm not sure if this is really as super basic as it sounds or not, but here's a couple of thoughts that might help:

Assuming it's an integer, can you simply test for it being 10,000 or greater (or -10,000 or less)?

if (abs(numberToTest) > 9999) {
    // Number has 4 or more digits

} else {
    // Number has 3 or fewer digits
}

Alternatively, if you're dealing with decimal values, you could try this:

NSString *stringToTest = [NSString stringWithFormat:@"%f", numberToTest];

// If you want to exclude the decimal place from the calculation
stringToTest = [stringToTest stringByReplacingOccurrencesOfString:@"." 
                                                       withString:@""];

// If you want to include a negative sign from the calculation
stringToTest = [stringToTest stringByReplacingOccurrencesOfString:@"-" 
                                                       withString:@""];
if (stringToTest.length > 4) {
    // String has 5 or more digits

} else {
    // String has 4 or fewer digits

}

Anyway, you didn't give a ton of detail, but maybe this solves your problem.

다른 팁

if its an int you could just subtract the number minus 9999 and determine if the result is negitive or positive but i assume its more complex than this

Yes you could just use an if statement

if (number > 9999)

print" we are in the 10000 range";

else

print " we are in less than 10000";

Is one line short enough?

let moreThanFourDigits = String(yourNumber).count > 4

Here I simply transform the number into a string and count the characters.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top