Last active
March 10, 2016 09:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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