I want to extract 1 decimal float number from existing float number.
I have done this in Objective-C: Make a float only show two decimal places
Any idea how to make it happen in Swift?
I want to extract 1 decimal float number from existing float number.
I have done this in Objective-C: Make a float only show two decimal places
Any idea how to make it happen in Swift?
You can make the same in swift :
var formatter : NSString = NSString(format: "%.01f", myFloat)
Or like you want in one line :
println("Pro Forma:- \n Total Experience(In Years) = "+(NSString(format: "%.01f", myFloat)))
This work too with the old NSLog (but prefer println) :
NSLog("Pro Forma:- \n Total Experience(In Years) = %.01f \n", myFloat)
You can try this
var experience = 10.25
println("Pro Forma:- \n Total Experience(In Years) = " + NSString(format: "%.01f", experience))
How about an infix operator?
// 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)
I've tried to do it with generics, but I can't see how. To make it work with multiple types, just overload it for those types - e.g.
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)
}