我想从现有的浮点数中提取1个十进制浮点数。
我在Objective-C中完成了这个: Make a float only show two decimal places
任何想法如何在Swift中实现?
答案 0 :(得分:9)
你可以在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)
答案 1 :(得分:2)
你可以试试这个
var experience = 10.25
println("Pro Forma:- \n Total Experience(In Years) = " + NSString(format: "%.01f", experience))
答案 2 :(得分:2)
中缀运营商怎么样?
// 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)
}