Question

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...

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top