【发布时间】:2014-06-13 07:08:02
【问题描述】:
我想从现有浮点数中提取 1 个十进制浮点数。
我在 Objective-C 中做过这个: Make a float only show two decimal places
知道如何在 Swift 中实现它吗?
【问题讨论】:
标签: objective-c swift xcode6
我想从现有浮点数中提取 1 个十进制浮点数。
我在 Objective-C 中做过这个: Make a float only show two decimal places
知道如何在 Swift 中实现它吗?
【问题讨论】:
标签: objective-c swift xcode6
你可以在 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)
【讨论】:
你可以试试这个
var experience = 10.25
println("Pro Forma:- \n Total Experience(In Years) = " + NSString(format: "%.01f", experience))
【讨论】:
中缀运算符怎么样?
// 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)
}
【讨论】: