zoukankan      html  css  js  c++  java
  • swift格式化输出

    以2为小数输出float a = 1.234567

    在oc中可以借助NSLog格式输出

    NSLog(@"float:%.2f",a);

    // 输出:

    // double:1.23

     

    在SWIFT中,String 的格式化初始方法可以帮助我们利用格式化的字符串:

    let format = String(format:"%.2f",a)

    print("double:(format)")

    // 输出:

    // double:1.23

     

    如果我们需要大量使用类似的字符串格式化功能的话,我们最好为 Double 写一个扩展:

    extension Double {

        func format(f: String) -> String {

            return String(format: "%(f)f", self)

        }

    }

    这样,在使用字符串插值和 print 的时候就能方便一些了:

    let f = ".2"

    print("double:(b.format(f))")

    参考:http://swifter.tips/output-format/

  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/Leean/p/5464580.html
Copyright © 2011-2022 走看看