Swift Formatting String to have 2 decimal numbers if it is not a whole number
You can extend FloatingPoint
to check if it is a whole number and use a condition to set the minimumFractionDigits
property of the NumberFormatter
to 0 in case it is true otherwise set it to 2:
extension Formatter {
static let custom: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
return formatter
}()
}
extension FloatingPoint {
var isWholeNumber: Bool { isNormal ? self == rounded() : isZero }
var custom: String {
Formatter.custom.minimumFractionDigits = isWholeNumber ? 0 : 2
return Formatter.custom.string(for: self) ?? ""
}
}
Playground testing:
1.0.custom // "1"
1.5.custom // "1.50"
1.75.custom // "1.75"
Round up double to 2 decimal places
Use a format string to round up to two decimal places and convert the double
to a String
:
let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = String(format: "%.2f", currentRatio)
Example:
let myDouble = 3.141
let doubleStr = String(format: "%.2f", myDouble) // "3.14"
If you want to round up your last decimal place, you could do something like this (thanks Phoen1xUK):
let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"
forcing a number to be displayed with 2 decimal places using swift
The Swift String type has an initializer that takes a format string: String(format:args:...)
Your code might look like this:
GrossTotal.text = String(format: "%.2f", gt)
EDIT: I had an "@" in front of the string, which is an Objective-C habit.
EDIT: Typing error resolved.
Formatting decimal places with unknown number
A Float
uses a binary (IEEE 754) representation and cannot represent
all decimal fractions precisely. For example,
let x : Float = 123.456
stores in x
the bytes 42f6e979
, which is approximately 123.45600128173828
. So does x
have 3 or 14 fractional digits?
You can use NSNumberFormatter
if you specify a maximum number
of decimal digits that should be presented:
let fmt = NSNumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0
println(fmt.stringFromNumber(123)!) // 123
println(fmt.stringFromNumber(123.4)!) // 123.4
println(fmt.stringFromNumber(123.45)!) // 123.45
println(fmt.stringFromNumber(123.456)!) // 123.456
println(fmt.stringFromNumber(123.4567)!) // 123.457
Swift 3/4 update:
let fmt = NumberFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0
print(fmt.string(for: 123.456)!) // 123.456
Swift - How to remove a decimal from a float if the decimal is equal to 0?
Swift 3/4:
var distanceFloat1: Float = 5.0
var distanceFloat2: Float = 5.540
var distanceFloat3: Float = 5.03
extension Float {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
print("Value \(distanceFloat1.clean)") // 5
print("Value \(distanceFloat2.clean)") // 5.54
print("Value \(distanceFloat3.clean)") // 5.03
Swift 2 (Original answer)
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue
distanceLabel.text = String(format: distanceFloat == floor(distanceFloat) ? “%.0f" : "%.1f", distanceFloat) + "Km"
Or as an extension:
extension Float {
var clean: String {
return self % 1 == 0 ? String(format: "%.0f", self) : String(self)
}
}
How I can print Double with 2 digit after point and hide if they are zero?
You could try this
func format(_ x: Double) -> String {
if Double(Int(x)) == x {
return String(Int(x))
} else {
let numberFormatter = NumberFormatter()
numberFormatter.maximumFractionDigits = 2
numberFormatter.minimumFractionDigits = 2
guard let s = numberFormatter.string(for: x) else {
fatalError("Couldn't format number")
}
return s
}
}
format(5.12) //"5.12"
format(5.0) //"5"
format(5.10) //"5.10"
Precision String Format Specifier In Swift
My best solution so far, following from David's response:
import Foundation
extension Int {
func format(f: String) -> String {
return String(format: "%\(f)d", self)
}
}
extension Double {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}
let someInt = 4, someIntFormat = "03"
println("The integer number \(someInt) formatted with \"\(someIntFormat)\" looks like \(someInt.format(someIntFormat))")
// The integer number 4 formatted with "03" looks like 004
let someDouble = 3.14159265359, someDoubleFormat = ".3"
println("The floating point number \(someDouble) formatted with \"\(someDoubleFormat)\" looks like \(someDouble.format(someDoubleFormat))")
// The floating point number 3.14159265359 formatted with ".3" looks like 3.142
I think this is the most Swift-like solution, tying the formatting operations directly to the data type. It may well be that there is a built-in library of formatting operations somewhere, or maybe it will be released soon. Keep in mind that the language is still in beta.
Format float value with 2 decimal places
You can use standard string formatting specifiers to round to an arbitrary number of decimal places. Specifically %.nf
where n
is the number of decimal places you require:
let twoDecimalPlaces = String(format: "%.2f", 10.426123)
Assuming you want to display the number on each of the l*
labels:
@IBAction func Berechnen(sender: AnyObject) {
var Zahl = (txt.text as NSString).floatValue
l5.text = String(format: "%.2f", (Zahl / 95) * 100)
l10.text = String(format: "%.2f", (Zahl / 90) * 100)
l15.text = String(format: "%.2f", (Zahl / 85) * 100)
l20.text = String(format: "%.2f", (Zahl / 80) * 100)
l25.text = String(format: "%.2f", (Zahl / 75) * 100)
l30.text = String(format: "%.2f", (Zahl / 70) * 100)
l35.text = String(format: "%.2f", (Zahl / 65) * 100)
l40.text = String(format: "%.2f", (Zahl / 60) * 100)
}
Related Topics
Recursivedescription Method in Swift
How to Set Image in Tabbar Not Tint Color in iOS
When Do App Sources Need to Be Included in Test Targets
Format Uilabel with Bullet Points
Broken Uisearchbar Animation Embedded in Navigationitem
How to Add Uipickerview into Uialertcontroller (Alert or Actionsheet) in Swift
How to Show a View on the First Launch Only
How to Use Pull to Refresh in Swift
Integration New Facebook Sdk by Swift
Issue with Unsafepointer<Uint8> in SQLite Project in Swift
Migrating from Uiwebview to Wkwebview
Open Link to Facebook Page from iOS App
Convert Mkcoordinateregion to Mkmaprect
Display Done Button on Uipickerview
Showing the File Download Progress with Nsurlsessiondatatask