我正在編寫一個單元測試,以確定字符串值是否出現2位有效數字,即。 「N.NN」我怎樣才能檢查一個浮動有兩個有效數字?
strokeValue = [NSString stringWithFormat:@"%.2f",someFloatValue];
我該如何編寫一個測試,斷言,我的字符串總是有2個小數位?
我正在編寫一個單元測試,以確定字符串值是否出現2位有效數字,即。 「N.NN」我怎樣才能檢查一個浮動有兩個有效數字?
strokeValue = [NSString stringWithFormat:@"%.2f",someFloatValue];
我該如何編寫一個測試,斷言,我的字符串總是有2個小數位?
由於您使用的是%.2f
格式說明,通過定義格式的浮點值,結果字符串將始終有兩位小數。如果someFloatValue
是5,您將得到5.00。如果someFloatValue
是3.1415926,你將得到3.14。
有沒有必要測試。對於給定的格式說明符,它將始終如此。
編輯:它發生在我身上,您可能確實想確認,實際上您正在使用正確的格式說明符。檢查結果字符串的一種方法是:
NSRange range = [strokeValue rangeOfString:@"."];
assert(range.location != NSNotFound && range.location == strokeValue.length - 3, @"String doesn't have two decimals places");
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
}
(未經測試)