I wrote a string extension
extension String {
func formatDoubleToString(value: Double, places: Int) -> String {
var result : String
if places == 1 {
result = String(format: "%.1f", value)
}
else if places == 2 {
result = String(format: "%.2f", value)
}
else {
result = String(format: "%.f", value)
}
return result
}
All my test on this extension pass except these ones where I work with .999 :
Display 99.99 with 1 decimal place 99.9
Display 9999.999 with two decimal places 9999.99
func testStringExtentionFormatDoubleToStringPlaces1_1(){
let result: String = String().formatDoubleToString(value: 99.99, places: 1)
XCTAssert(result == "99.9", "Display 99.99 with 1 decimal place 99.9")
}
func testStringExtentionFormatDoubleToStringZeroPlaces2_7(){
let result: String = String().formatDoubleToString(value: 9999.999, places: 2)
XCTAssert(result == "9999.99", "Display 9999.999 with two decimal places 9999.99")
}