【问题标题】:Specify floating point number accuracy in NSString在 NSString 中指定浮点数精度
【发布时间】:2013-05-14 11:09:46
【问题描述】:

我试图在我的 NSString 中指定我的浮点数的准确性,但我不断收到此错误:

格式指定类型'double',但参数类型为'NSString *'

这是我的代码:

NSString *tmplabel = [tmp description];
temp.text = [NSString  stringWithFormat: @"%.fº", tmplabel];

我做错了什么?

【问题讨论】:

  • tmplabel 是 NSString 的对象。所以,你不能使用 %f。使用 %@ 作为 NSString 的对象
  • 你想要输出什么?
  • @DharaParekh 感谢您的评论,但如果我使用 %@ 则无法控制浮点数的准确性。基本上,目前的数字是 8.xx 我希望它是 8.x 所以我需要使用 %f??
  • 所以我问你预期的 o/p。查看我的答案以获得所需的输出...

标签: objective-c floating-point nsstring string-formatting


【解决方案1】:

您的 tmplabel 是 NSString,它应该是 double

如果您确定 tmplabel 包含一个可以解析为简单双精度的数字,那么您可以在其上使用 doubleValue。否则,您可能需要通过错误处理等进行更精细的转换。

这里有一个简单实用的方法:

temp.text = [NSString  stringWithFormat: @"%.fº", [tmplabel doubleValue]];

doubleValue 方法(及其近亲integerValue 和类似方法)解释字符串的内容,如果字符串的开头可以读取为数字,它将转换为您并将其作为适当的原始类型返回。在您的情况下,原始类型是double

您不能将类型从对象(任何 NS*)转换为原始类型,但总是必须经过某种解释或程序转换。

最后,请注意,直接在用户输入上使用 doubleValue 是一种快捷方式,您将在某个时候重新访问它,因此请记住使用数字格式化程序或 @987654331 重新实现它@ 之后。要了解原因,请尝试输入非数字数据,看看您对结果是否满意。

最后,要按您的要求实际设置精度(即小数点后的小数位数),请参阅下面的王子 answerDharaParekh's

【讨论】:

  • 这很好用,谢谢。所以基本上你的类型转换在这里?
  • 非常感谢您的解释。确实非常有用:)
【解决方案2】:

试试这个

NSString *tmplabel = [tmp description];
temp.text = [NSString  stringWithFormat: @"%.f", [tmplabel doubleValue]];

【讨论】:

    【解决方案3】:

    试试这个:

    NSString *tmplabel = [tmp description];
    float tmp = [tmplabel floatValue];
    temp.text = [NSString  stringWithFormat: @"%.1f", tmp];
    

    【讨论】:

      【解决方案4】:
      {
      temp.text = [NSString  stringWithFormat: @"%.1f", tmplabel];
      }
      

      您可以更改 f 前面的数字来指定准确度。

      【讨论】:

        猜你喜欢
        • 2019-05-22
        • 1970-01-01
        • 2020-02-03
        • 1970-01-01
        • 2018-02-23
        • 1970-01-01
        • 2020-08-31
        • 2012-01-13
        • 1970-01-01
        相关资源
        最近更新 更多