【发布时间】:2014-07-25 22:08:29
【问题描述】:
下面是我之前如何将浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查看了文档和电子书,但无法弄清楚。谢谢!
【问题讨论】:
标签: swift
下面是我之前如何将浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查看了文档和电子书,但无法弄清楚。谢谢!
【问题讨论】:
标签: swift
import Foundation // required for String(format: _, _)
print(String(format: "a float number: %.2f", 1.0321))
【讨论】:
println(String(format: "a float number: %.5f", 1.0321))
import Cocoa。
到目前为止我最好的解决方案,来自David's response:
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
我认为这是最类似于 Swift 的解决方案,将格式化操作直接绑定到数据类型。很可能某处有一个内置的格式化操作库,或者它很快就会发布。请记住,该语言仍处于测试阶段。
【讨论】:
Text("\(someDouble, specifier: "%.3f")")
我发现String.localizedStringWithFormat 工作得很好:
例子:
let value: Float = 0.33333
let unit: String = "mph"
yourUILabel.text = String.localizedStringWithFormat("%.2f %@", value, unit)
【讨论】:
这是一种非常快速和简单的方式,不需要复杂的解决方案。
let duration = String(format: "%.01f", 3.32323242)
// result = 3.3
【讨论】:
Col 16: 'init' has been renamed to 'init(describing:)'
这里的大多数答案都是有效的。但是,如果您经常格式化数字,请考虑扩展 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))")
控制台显示:
The velocity is 12.33
The velocity is 12.3
extension Float {
func string(fractionDigits:Int) -> String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = fractionDigits
formatter.maximumFractionDigits = fractionDigits
return formatter.string(from: NSNumber(value: self)) ?? "\(self)"
}
}
【讨论】:
NSNumberFormatter,喜欢这个答案。其他投票率高的答案根本无法反映设备区域设置(例如,在某些区域设置中,他们使用逗号作为小数位;这反映了这一点;其他答案则没有)。
NSNumberFormatter 的初始化速度相当慢。如果可能,它有助于定义一个并重用它。也就是说,我在这里阅读这个问题是因为在我的情况下这是不可能的。
你不能(还)用字符串插值来做到这一点。你最好的选择仍然是 NSString 格式:
println(NSString(format:"%.2f", sqrt(2.0)))
从 python 推断,一个合理的语法似乎是:
@infix func % (value:Double, format:String) -> String {
return NSString(format:format, value)
}
然后允许您将它们用作:
M_PI % "%5.3f" // "3.142"
您可以为所有数字类型定义类似的运算符,遗憾的是我还没有找到使用泛型的方法。
Swift 5 更新
至少从 Swift 5 开始,String 直接支持 format: 初始化器,因此无需使用 NSString 并且不再需要 @infix 属性,这意味着上面的示例应编写为:
println(String(format:"%.2f", sqrt(2.0)))
func %(value:Double, format:String) -> String {
return String(format:format, value)
}
Double.pi % "%5.3f" // "3.142"
【讨论】:
[NSString stringWithFormat...的快捷版
为什么要这么复杂?你可以改用这个:
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
在 Playground 中查看它的工作原理。
PS:解决方案来自:http://rrike.sh/xcode/rounding-various-decimal-places-swift/
【讨论】:
import Foundation
extension CGFloat {
var string1: String {
return String(format: "%.1f", self)
}
var string2: String {
return String(format: "%.2f", self)
}
}
let offset = CGPoint(1.23, 4.56)
print("offset: \(offset.x.string1) x \(offset.y.string1)")
// offset: 1.2 x 4.6
【讨论】:
更优雅通用的解决方案是重写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]
【讨论】:
"Hello %@, This is pi : %.2f" % ["World", M_PI] 确实有效,但奇怪的是 "%@ %@" % ["Hello", "World"] raise can't unsafeBitCast... 猜猜这将在下一个版本中修复。
, 在 Swift 和大多数语言中不是有效的字符运算符。而imo,最好使用其他语言中已经存在的% 运算符。见developer.apple.com/library/ios/documentation/Swift/Conceptual/…
(5.2).rounded()
// 5.0
(5.5).rounded()
// 6.0
(-5.2).rounded()
// -5.0
(-5.5).rounded()
// -6.0
func rounded(_ rule: FloatingPointRoundingRule) -> Double
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"
var x = 5.2
x.round()
// x == 5.0
var y = 5.5
y.round()
// y == 6.0
var z = -5.5
z.round()
// z == -6.0
mutating func round(_ rule: FloatingPointRoundingRule)
// Equivalent to the C 'round' function:
var w = 6.5
w.round(.toNearestOrAwayFromZero)
// w == 7.0
// Equivalent to the C 'trunc' function:
var x = 6.5
x.round(.towardZero)
// x == 6.0
// Equivalent to the C 'ceil' function:
var y = 6.5
y.round(.up)
// y == 7.0
// Equivalent to the C 'floor' function:
var z = 6.5
z.round(.down)
// z == 6.0
extension Numeric {
private func _precision(number: NSNumber, formatter: NumberFormatter) -> Self? {
if let formatedNumString = formatter.string(from: number),
let formatedNum = formatter.number(from: formatedNumString) {
return formatedNum as? Self
}
return nil
}
private func toNSNumber() -> NSNumber? {
if let num = self as? NSNumber { return num }
guard let string = self as? String, let double = Double(string) else { return nil }
return NSNumber(value: double)
}
func precision(_ minimumFractionDigits: Int,
roundingMode: NumberFormatter.RoundingMode = NumberFormatter.RoundingMode.halfUp) -> Self? {
guard let number = toNSNumber() else { return nil }
let formatter = NumberFormatter()
formatter.minimumFractionDigits = minimumFractionDigits
formatter.roundingMode = roundingMode
return _precision(number: number, formatter: formatter)
}
func precision(with numberFormatter: NumberFormatter) -> String? {
guard let number = toNSNumber() else { return nil }
return numberFormatter.string(from: number)
}
}
_ = 123.44.precision(2)
_ = 123.44.precision(3, roundingMode: .up)
let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 1
numberFormatter.groupingSeparator = " "
let num = 222.3333
_ = num.precision(2)
func option1<T: Numeric>(value: T, numerFormatter: NumberFormatter? = nil) {
print("Type: \(type(of: value))")
print("Original Value: \(value)")
let value1 = value.precision(2)
print("value1 = \(value1 != nil ? "\(value1!)" : "nil")")
let value2 = value.precision(5)
print("value2 = \(value2 != nil ? "\(value2!)" : "nil")")
if let value1 = value1, let value2 = value2 {
print("value1 + value2 = \(value1 + value2)")
}
print("")
}
func option2<T: Numeric>(value: T, numberFormatter: NumberFormatter) {
print("Type: \(type(of: value))")
print("Original Value: \(value)")
let value1 = value.precision(with: numberFormatter)
print("formated value = \(value1 != nil ? "\(value1!)" : "nil")\n")
}
func test(with double: Double) {
print("===========================\nTest with: \(double)\n")
let float = Float(double)
let float32 = Float32(double)
let float64 = Float64(double)
let float80 = Float80(double)
let cgfloat = CGFloat(double)
// Exapmle 1
print("-- Option1\n")
option1(value: double)
option1(value: float)
option1(value: float32)
option1(value: float64)
option1(value: float80)
option1(value: cgfloat)
// Exapmle 2
let numberFormatter = NumberFormatter()
numberFormatter.formatterBehavior = .behavior10_4
numberFormatter.minimumIntegerDigits = 1
numberFormatter.minimumFractionDigits = 4
numberFormatter.maximumFractionDigits = 9
numberFormatter.usesGroupingSeparator = true
numberFormatter.groupingSeparator = " "
numberFormatter.groupingSize = 3
print("-- Option 2\n")
option2(value: double, numberFormatter: numberFormatter)
option2(value: float, numberFormatter: numberFormatter)
option2(value: float32, numberFormatter: numberFormatter)
option2(value: float64, numberFormatter: numberFormatter)
option2(value: float80, numberFormatter: numberFormatter)
option2(value: cgfloat, numberFormatter: numberFormatter)
}
test(with: 123.22)
test(with: 1234567890987654321.0987654321)
===========================
Test with: 123.22
-- Option1
Type: Double
Original Value: 123.22
value1 = 123.22
value2 = 123.22
value1 + value2 = 246.44
Type: Float
Original Value: 123.22
value1 = nil
value2 = nil
Type: Float
Original Value: 123.22
value1 = nil
value2 = nil
Type: Double
Original Value: 123.22
value1 = 123.22
value2 = 123.22
value1 + value2 = 246.44
Type: Float80
Original Value: 123.21999999999999886
value1 = nil
value2 = nil
Type: CGFloat
Original Value: 123.22
value1 = 123.22
value2 = 123.22
value1 + value2 = 246.44
-- Option 2
Type: Double
Original Value: 123.22
formatted value = 123.2200
Type: Float
Original Value: 123.22
formatted value = 123.220001221
Type: Float
Original Value: 123.22
formatted value = 123.220001221
Type: Double
Original Value: 123.22
formatted value = 123.2200
Type: Float80
Original Value: 123.21999999999999886
formatted value = nil
Type: CGFloat
Original Value: 123.22
formatted value = 123.2200
===========================
Test with: 1.2345678909876544e+18
-- Option1
Type: Double
Original Value: 1.2345678909876544e+18
value1 = 1.23456789098765e+18
value2 = 1.23456789098765e+18
value1 + value2 = 2.4691357819753e+18
Type: Float
Original Value: 1.234568e+18
value1 = nil
value2 = nil
Type: Float
Original Value: 1.234568e+18
value1 = nil
value2 = nil
Type: Double
Original Value: 1.2345678909876544e+18
value1 = 1.23456789098765e+18
value2 = 1.23456789098765e+18
value1 + value2 = 2.4691357819753e+18
Type: Float80
Original Value: 1234567890987654400.0
value1 = nil
value2 = nil
Type: CGFloat
Original Value: 1.2345678909876544e+18
value1 = 1.23456789098765e+18
value2 = 1.23456789098765e+18
value1 + value2 = 2.4691357819753e+18
-- Option 2
Type: Double
Original Value: 1.2345678909876544e+18
formatted value = 1 234 567 890 987 650 000.0000
Type: Float
Original Value: 1.234568e+18
formatted value = 1 234 567 939 550 610 000.0000
Type: Float
Original Value: 1.234568e+18
formatted value = 1 234 567 939 550 610 000.0000
Type: Double
Original Value: 1.2345678909876544e+18
formatted value = 1 234 567 890 987 650 000.0000
Type: Float80
Original Value: 1234567890987654400.0
formatted value = nil
Type: CGFloat
Original Value: 1.2345678909876544e+18
formatted value = 1 234 567 890 987 650 000.0000
【讨论】:
斯威夫特 4
let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)
【讨论】:
你仍然可以在 Swift 中使用 NSLog,就像在 Objective-C 中一样,只是没有 @ 符号。
NSLog("%.02f %.02f %.02f", r, g, b)
编辑:在使用 Swift 一段时间后,我还想添加这个变体
var r=1.2
var g=1.3
var b=1.4
NSLog("\(r) \(g) \(b)")
输出:
2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4
【讨论】:
extension Double {
func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
return Double(formattedString)!
}
}
1.3333.formatWithDecimalPlaces(2)
【讨论】:
到目前为止,获得最多票数的答案都依赖于 NSString 方法,并且将要求您已导入 Foundation。
尽管如此,您仍然可以访问 NSLog。
所以我认为这个问题的答案,如果你问如何在 Swift 中继续使用 NSLog,很简单:
import Foundation
【讨论】:
//It will more help, by specify how much decimal Point you want.
let decimalPoint = 2
let floatAmount = 1.10001
let amountValue = String(format: "%0.*f", decimalPoint, floatAmount)
【讨论】:
这里有一个“纯”的快速解决方案
var d = 1.234567
operator infix ~> {}
@infix func ~> (left: Double, right: Int) -> String {
if right == 0 {
return "\(Int(left))"
}
var k = 1.0
for i in 1..right+1 {
k = 10.0 * k
}
let n = Double(Int(left*k)) / Double(k)
return "\(n)"
}
println("\(d~>2)")
println("\(d~>1)")
println("\(d~>0)")
【讨论】:
扩展的力量
extension Double {
var asNumber:String {
if self >= 0 {
var formatter = NSNumberFormatter()
formatter.numberStyle = .NoStyle
formatter.percentSymbol = ""
formatter.maximumFractionDigits = 1
return "\(formatter.stringFromNumber(self)!)"
}
return ""
}
}
let velocity:Float = 12.32982342034
println("The velocity is \(velocity.toNumber)")
输出: 速度为 12.3
【讨论】:
少打字方式:
func fprint(format: String, _ args: CVarArgType...) {
print(NSString(format: format, arguments: getVaList(args)))
}
【讨论】:
Double 和 CGFloat 类型的扩展怎么样:
extension Double {
func formatted(_ decimalPlaces: Int?) -> String {
let theDecimalPlaces : Int
if decimalPlaces != nil {
theDecimalPlaces = decimalPlaces!
}
else {
theDecimalPlaces = 2
}
let theNumberFormatter = NumberFormatter()
theNumberFormatter.formatterBehavior = .behavior10_4
theNumberFormatter.minimumIntegerDigits = 1
theNumberFormatter.minimumFractionDigits = 1
theNumberFormatter.maximumFractionDigits = theDecimalPlaces
theNumberFormatter.usesGroupingSeparator = true
theNumberFormatter.groupingSeparator = " "
theNumberFormatter.groupingSize = 3
if let theResult = theNumberFormatter.string(from: NSNumber(value:self)) {
return theResult
}
else {
return "\(self)"
}
}
}
用法:
let aNumber: Double = 112465848348508.458758344
Swift.print("The number: \(aNumber.formatted(2))")
打印:112 465 848 348 508.46
【讨论】:
iOS 15+ 之后推荐这个解决方案:
2.31234.formatted(.number.precision(.fractionalLength(1)))
【讨论】:
你也可以这样创建算子
operator infix <- {}
func <- (format: String, args:[CVarArg]) -> String {
return String(format: format, arguments: args)
}
let str = "%d %.1f" <- [1453, 1.123]
【讨论】:
还有四舍五入:
extension Float
{
func format(f: String) -> String
{
return NSString(format: "%\(f)f", self)
}
mutating func roundTo(f: String)
{
self = NSString(format: "%\(f)f", self).floatValue
}
}
extension Double
{
func format(f: String) -> String
{
return NSString(format: "%\(f)f", self)
}
mutating func roundTo(f: String)
{
self = NSString(format: "%\(f)f", self).doubleValue
}
}
x = 0.90695652173913
x.roundTo(".2")
println(x) //0.91
【讨论】:
使用下面的方法
let output = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)
println(output)
【讨论】:
Vincent Guerci 的 ruby / python % 运算符的一个版本,针对 Swift 2.1 进行了更新:
func %(format:String, args:[CVarArgType]) -> String {
return String(format:format, arguments:args)
}
"Hello %@, This is pi : %.2f" % ["World", M_PI]
【讨论】:
上面有很多很好的答案,但有时一个模式比“%.3f”那种 gobbledygook 更合适。这是我在 Swift 3 中使用 NumberFormatter 的看法。
extension Double {
func format(_ pattern: String) -> String {
let formatter = NumberFormatter()
formatter.format = pattern
return formatter.string(from: NSNumber(value: self))!
}
}
let n1 = 0.350, n2 = 0.355
print(n1.format("0.00#")) // 0.35
print(n2.format("0.00#")) // 0.355
这里我希望始终显示 2 个小数,但仅当它不为零时才显示第三个。
【讨论】:
Swift 4 Xcode 10 更新
extension Double {
var asNumber:String {
if self >= 0 {
let formatter = NumberFormatter()
formatter.numberStyle = .none
formatter.percentSymbol = ""
formatter.maximumFractionDigits = 2
return "\(formatter.string(from: NSNumber(value: self)) ?? "")"
}
return ""
}
}
【讨论】:
@infix func ^(left:Double, right: Int) -> NSNumber {
let nf = NSNumberFormatter()
nf.maximumSignificantDigits = Int(right)
return nf.numberFromString(nf.stringFromNumber(left))
}
let r = 0.52264
let g = 0.22643
let b = 0.94837
println("this is a color: \(r^3) \(g^3) \(b^3)")
// this is a color: 0.523 0.226 0.948
【讨论】:
我不知道 两个 位小数,但这里是您如何打印小数点为零的浮点数,所以我想可能是 2 位、3 位...(注意:您必须将 CGFloat 转换为 Double 以传递给 String(format:) 否则它会看到零值)
func logRect(r: CGRect, _ title: String = "") {
println(String(format: "[ (%.0f, %.0f), (%.0f, %.0f) ] %@",
Double(r.origin.x), Double(r.origin.y), Double(r.size.width), Double(r.size.height), title))
}
【讨论】:
Swift2 示例:iOS 设备的屏幕宽度格式化浮点数去除小数
print(NSString(format: "Screen width = %.0f pixels", CGRectGetWidth(self.view.frame)))
【讨论】:
@克里斯蒂安·迪特里希:
代替:
var k = 1.0
for i in 1...right+1 {
k = 10.0 * k
}
let n = Double(Int(left*k)) / Double(k)
return "\(n)"
也可以是:
let k = pow(10.0, Double(right))
let n = Double(Int(left*k)) / k
return "\(n)"
[更正:] 很抱歉混淆* - 这当然适用于双打。我认为,最实用的(如果您希望数字四舍五入,而不是截断)它会是这样的:
infix operator ~> {}
func ~> (left: Double, right: Int) -> Double {
if right <= 0 {
return round(left)
}
let k = pow(10.0, Double(right))
return round(left*k) / k
}
仅适用于 Float,只需将 Double 替换为 Float,将 pow 替换为 powf,将 round 替换为 roundf。
更新:我发现使用 return 最实用键入 Double 而不是 String。它对字符串输出的工作方式相同,即:
println("Pi is roughly \(3.1415926 ~> 3)")
打印:Pi 大约为 3.142
所以你可以用同样的方式来处理字符串(你甚至可以写:println(d ~> 2)),但你也可以直接用它来舍入值,即:
d = Double(slider.value) ~> 2
或者任何你需要的……
【讨论】: