【问题标题】:How to get 1 decimal Float in swift [duplicate]如何快速获得 1 个小数浮点数 [重复]
【发布时间】:2014-06-13 07:08:02
【问题描述】:

我想从现有浮点数中提取 1 个十进制浮点数。

我在 Objective-C 中做过这个: Make a float only show two decimal places

知道如何在 Swift 中实现它吗?

【问题讨论】:

    标签: objective-c swift xcode6


    【解决方案1】:

    你可以在 swift 中做同样的事情:

    var formatter : NSString = NSString(format: "%.01f", myFloat)
    

    或者像你想要的那样:

    println("Pro Forma:- \n Total Experience(In Years) = "+(NSString(format: "%.01f", myFloat)))
    

    这也适用于旧的 NSLog(但更喜欢 println):

    NSLog("Pro Forma:- \n Total Experience(In Years) = %.01f \n", myFloat)
    

    【讨论】:

    • 这在技术上是正确的,但是如何在不为字符串添加一行的情况下打印它。例如下面的代码不会编译:
    • println("Pro Forma:- \n Total Experience(In Years) = (NSString(format: "%.01f", experience))") // 这里的经验是浮动的,我想为小数点后 1 位。 (这在 Objective-C 中是可能的)
    • 这个编译为我 println("Pro Forma:- \n Total Experience(In Years) = "+(NSString(format: "%.01f", experience)))
    【解决方案2】:

    你可以试试这个

    var experience = 10.25
    println("Pro Forma:- \n Total Experience(In Years) = " + NSString(format: "%.01f", experience))
    

    【讨论】:

      【解决方案3】:

      中缀运算符怎么样?

      // Declare this at file level, anywhere in you project. 
      // Expressions of the form 
      //     "format string" %% doubleValue
      // will return a string. If the string is not a well formed format string, you'll
      // just get the string back! If you use incorrect format specifiers (e.g. %d for double)
      // you'll get 0 as the formatted value.
      operator infix %% { }
      @infix func %% (format: String, value: Double) -> String {
          return NSString(format:format, value)
      }
      
      // ...
      // You can then use it anywhere
      let experience = 1.234
      println("Pro Forma:- \n Total Experience(In Years) = %.01f" %% experience)
      

      我试过用泛型来做,但我不知道怎么做。要使其适用于多种类型,只需为这些类型重载它 - 例如

      operator infix %% { }
      @infix func %% (format: String, value: Double) -> String {
          return NSString(format:format, value)
      }
      @infix func %% (format: String, value: Float) -> String {
          return NSString(format:format, value)
      }
      @infix func %% (format: String, value: Int) -> String {
          return NSString(format:format, value)
      }
      

      【讨论】:

      • 有趣!但是,如果您可以针对您编写的代码添加 cmets,这将非常有帮助。
      • 哪一部分需要评论?我目前正在尝试使用泛型使其工作,并在我完成后正确评论它!
      • 我刚开始使用 Swift。你能解释一下@infix 指令吗?
      • 你有这本书吗?它是免费的,而且非常重要。章节称为“操作符函数”,或者只是使用 iBook 搜索来查找 @infix。
      • 是的,我有来自 Apple 的书,将看看那部分。好吧,cmets 的描述性足以捕捉。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多