Skip to content

Instantly share code, notes, and snippets.

@atika
Last active March 10, 2016 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atika/a53c234c51bb1b141bdb to your computer and use it in GitHub Desktop.
Save atika/a53c234c51bb1b141bdb to your computer and use it in GitHub Desktop.
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