【问题标题】:How can I check if a float has two significant figures?如何检查浮点数是否有两个有效数字?
【发布时间】:2026-01-19 11:55:01
【问题描述】:

我正在编写一个单元测试来确定一个字符串值是否以 2 个有效数字出现,即。 “NN”

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

如何编写一个断言,我的字符串总是有 2 位小数的测试?

【问题讨论】:

    标签: objective-c cocoa-touch unit-testing floating-point nsstring


    【解决方案1】:

    由于您使用%.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");
    

    【讨论】:

      【解决方案2】:
      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
      }
      

      (未经测试)

      【讨论】: