Sheehan Alam
Sheehan Alam

Reputation: 60869

How can I check if a float has two significant figures?

I am writing a unit test to determine if a string value appears with 2 significant figures, ie. "N.NN"

    strokeValue = [NSString stringWithFormat:@"%.2f",someFloatValue];

How can I write a test that asserts, my string always has 2 decimal places?

Upvotes: 0

Views: 214

Answers (2)

rmaddy
rmaddy

Reputation: 318804

Since you are formatting a float value using the %.2f format specifier, by definition, the resulting string will always have two decimal places. If someFloatValue is 5 you will get 5.00. If someFloatValue is 3.1415926 you will get 3.14.

There is no need to test. It will always be true with the given format specifier.

Edit: It occurs to me that you may actually want to confirm that in fact you are using the correct format specifier. One way to check the resulting string would be:

NSRange range = [strokeValue rangeOfString:@"."];
assert(range.location != NSNotFound && range.location == strokeValue.length - 3, @"String doesn't have two decimals places");

Upvotes: 3

Kevin
Kevin

Reputation: 56059

NSRegularExpression *regex = [NSRegularExpression  regularExpressionWithPattern:@"\.[0-9]{2}$" options:0 error:nil];
if([regex numberOfMatchesInString:strokeValue options:0 range:NSMakeRange(0, [strokeValue length])]) {
    // Passed
} else {
    // failed
}

(untested)

Upvotes: 1

Related Questions