Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Format a float value with desired numbers after the comma to a string. Doesn't display the comma if the number is a round value.
// Format a float value with desired numbers after the comma to a string. Doesn't display the comma if the number is a round value.
import Foundation
extension Double {
func toDecimalString(decimals: Int = 0) -> String {
let format = (self % 1 > 0 && decimals > 0) ? "%.\(decimals)f" : "%.0f"
return String(format:format, self)
}
}
extension CGFloat {
func toDecimalString(decimals: Int = 0) -> String {
let format = (self % 1 > 0 && decimals > 0) ? "%.\(decimals)f" : "%.0f"
return String(format:format, self)
}
}
let chiffre: Double = 20.25000
let float: CGFloat = 99.67
print(chiffre.toDecimalString(2)) //-> 20.25
print(chiffre.toDecimalString(1)) //-> 20.2
print(chiffre.toDecimalString(0)) //-> 20
print("--------")
print(float.toDecimalString(2)) //-> 99.67
print(float.toDecimalString(1)) //-> 99.7
print(float.toDecimalString(0)) //-> 100
print(float.toDecimalString()) //-> 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment