Swift中的精确字符串格式说明符

use*_*868 372 swift

下面是我之前将浮点数截断为两位小数的方法

NSLog(@" %.02f %.02f %.02f", r, g, b);
Run Code Online (Sandbox Code Playgroud)

我检查了文档和电子书,但还没弄清楚.谢谢!

rea*_*one 771

一个简单的方法是:

import Foundation // required for String(format: _, _)

print(String(format: "hex string: %X", 123456))
print(String(format: "a float number: %.5f", 1.0321))
Run Code Online (Sandbox Code Playgroud)

  • 我相信这是一个比接受的答案更好的答案.它更接近标准的c-style`printf`而无需编写单独的扩展. (74认同)
  • 不要忘记文件顶部的"导入基础". (9认同)
  • `println(String(格式:"浮点数:%.5f",1.0321))` (7认同)
  • 这比接受的答案要好,但仍然使用Foundation方法(桥接到Swift). (3认同)

Ant*_*kov 261

到目前为止,我的最佳解决方案是David的回应:

import Foundation

extension Int {
    func format(f: String) -> String {
        return String(format: "%\(f)d", self)
    }
}

extension Double {
    func format(f: String) -> String {
        return String(format: "%\(f)f", self)
    }
}

let someInt = 4, someIntFormat = "03"
println("The integer number \(someInt) formatted with \"\(someIntFormat)\" looks like \(someInt.format(someIntFormat))")
// The integer number 4 formatted with "03" looks like 004

let someDouble = 3.14159265359, someDoubleFormat = ".3"
println("The floating point number \(someDouble) formatted with \"\(someDoubleFormat)\" looks like \(someDouble.format(someDoubleFormat))")
// The floating point number 3.14159265359 formatted with ".3" looks like 3.142
Run Code Online (Sandbox Code Playgroud)

我认为这是最像Swift的解决方案,将格式化操作直接绑定到数据类型.很可能某个地方有一个内置的格式化操作库,或者它很快就会发布.请注意,该语言仍处于测试阶段.

  • 这不必要地复杂化.realityone的答案有效,而且更加简洁. (70认同)
  • 当然,如果你只使用一次.但是如果你想使用字符串插值(更具可读性)有更多格式化选项,那么你可以将所有格式扩展放在其他地方的文件中,并在整个项目中引用它.当然,理想情况下Apple应该提供格式库. (6认同)
  • 在 SwiftUI 中使用 `Text("\(someDouble, 说明符: "%.3f")")` (3认同)
  • 如果不将结果转换为String,此解决方案将无法在Swift 1.2中运行. (2认同)

Val*_*tin 125

我发现String.localizedStringWithFormat工作得很好:

例:

let value: Float = 0.33333
let unit: String = "mph"

yourUILabel.text = String.localizedStringWithFormat("%.2f %@", value, unit)
Run Code Online (Sandbox Code Playgroud)


fat*_*han 79

这是一种非常快速简单的方法,不需要复杂的解决方案.

let duration = String(format: "%.01f", 3.32323242)
// result = 3.3
Run Code Online (Sandbox Code Playgroud)


Don*_*onn 60

这里的大多数答案都有效.但是,如果您经常格式化数字,请考虑扩展Float类以添加返回格式化字符串的方法.请参阅下面的示例代码 这个通过使用数字格式化器和扩展来实现相同的目标.

extension Float {
    func string(fractionDigits:Int) -> String {
        let formatter = NSNumberFormatter()
        formatter.minimumFractionDigits = fractionDigits
        formatter.maximumFractionDigits = fractionDigits
        return formatter.stringFromNumber(self) ?? "\(self)"
    }
}

let myVelocity:Float = 12.32982342034

println("The velocity is \(myVelocity.string(2))")
println("The velocity is \(myVelocity.string(1))")
Run Code Online (Sandbox Code Playgroud)

控制台显示:

The velocity is 12.33
The velocity is 12.3
Run Code Online (Sandbox Code Playgroud)

SWIFT 3.1更新

extension Float {
    func string(fractionDigits:Int) -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = fractionDigits
        formatter.maximumFractionDigits = fractionDigits
        return formatter.string(from: NSNumber(value: self)) ?? "\(self)"
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我希望更多的人会使用`NSNumberFormatter`,就像这个答案一样.其他高度评价的答案只是无法反映设备区域设置(例如,在某些区域设置中,它们使用逗号表示小数位;这反映了这一点;其他答案则没有). (11认同)
  • 我希望看到的唯一改进是为任何给定的数字存储格式化程序 - NSNumberFormatters的构造成本很高. (3认同)

Dav*_*rry 35

你不能用(或)字符串插值来做.你最好的选择仍然是NSString格式:

println(NSString(format:"%.2f", sqrt(2.0)))
Run Code Online (Sandbox Code Playgroud)

从python推断,似乎合理的语法可能是:

@infix func % (value:Double, format:String) -> String {
    return NSString(format:format, value)
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将它们用作:

M_PI % "%5.3f"                // "3.142"
Run Code Online (Sandbox Code Playgroud)

您可以为所有数字类型定义类似的运算符,遗憾的是我还没有找到使用泛型的方法.

  • 如果你在Python中实现%,那么它应该是另一种方式."%5.3f"%M_PI (2认同)

Tia*_*ida 16

iOS 15+ 之后建议使用此解决方案:

2.31234.formatted(.number.precision(.fractionLength(1)))
Run Code Online (Sandbox Code Playgroud)

  • 它是 `.fractionalLength(...)`,而不是 `.fractionalLength(...)` (2认同)

neo*_*eye 13

import Foundation

extension CGFloat {
    var string1: String {
        return String(format: "%.1f", self)
    }
    var string2: String {
        return String(format: "%.2f", self)
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

let offset = CGPoint(1.23, 4.56)
print("offset: \(offset.x.string1) x \(offset.y.string1)")
// offset: 1.2 x 4.6
Run Code Online (Sandbox Code Playgroud)


小智 12

为什么要这么复杂?您可以使用此代替:

import UIKit

let PI = 3.14159265359

round( PI ) // 3.0 rounded to the nearest decimal
round( PI * 100 ) / 100 //3.14 rounded to the nearest hundredth
round( PI * 1000 ) / 1000 // 3.142 rounded to the nearest thousandth
Run Code Online (Sandbox Code Playgroud)

看它在Playground工作.

PS:解决方案来自:http://rrike.sh/xcode/rounding-various-decimal-places-swift/

  • 挑剔的事情.. 1.500000000只会是"1.5"而不是"1.50" (6认同)

Vin*_*rci 10

更优雅和通用的解决方案是重写ruby/python %运算符:

// Updated for beta 5
func %(format:String, args:[CVarArgType]) -> String {
    return NSString(format:format, arguments:getVaList(args))
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]
Run Code Online (Sandbox Code Playgroud)

  • 这似乎不迟于Xcode 6.1 GM修复. (3认同)

onm*_*133 7

斯威夫特4

let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)
Run Code Online (Sandbox Code Playgroud)

  • 对我来说有效:let string = String(format:“%.2f”,myString) (3认同)

Vas*_*huk 6

细节

Xcode 9.3,Swift 4.1

(5.2).rounded()
// 5.0
(5.5).rounded()
// 6.0
(-5.2).rounded()
// -5.0
(-5.5).rounded()
// -6.0
Run Code Online (Sandbox Code Playgroud)

用法

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述


hol*_*hol 5

您仍然可以在Objective-C中使用Swift中的NSLog,而不使用@符号.

NSLog("%.02f %.02f %.02f", r, g, b)
Run Code Online (Sandbox Code Playgroud)

编辑:在使用Swift一段时间之后,我想添加这个变体

    var r=1.2
    var g=1.3
    var b=1.4
    NSLog("\(r) \(g) \(b)")
Run Code Online (Sandbox Code Playgroud)

输出:

2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4
Run Code Online (Sandbox Code Playgroud)


Luc*_*rah 5

extension Double {
  func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
     let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
     return Double(formattedString)!
     }
 }

 1.3333.formatWithDecimalPlaces(2)
Run Code Online (Sandbox Code Playgroud)