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)
}
}
Swift - Remove Trailing Zeros From Double
In Swift 4 you can do it like that:
extension Double {
func removeZerosFromEnd() -> String {
let formatter = NumberFormatter()
let number = NSNumber(value: self)
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 16 //maximum digits in Double after dot (maximum precision)
return String(formatter.string(from: number) ?? "")
}
}
example of use: print (Double("128834.567891000").removeZerosFromEnd())
result: 128834.567891
You can also count how many decimal digits has your string:
import Foundation
extension Double {
func removeZerosFromEnd() -> String {
let formatter = NumberFormatter()
let number = NSNumber(value: self)
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = (self.components(separatedBy: ".").last)!.count
return String(formatter.string(from: number) ?? "")
}
}
Decimal values get remove when convert from String to Decimal in Swift
Like martin said. 12 and 12.00 is the same number. It doesn't mathematical matter how many 0 are behind the comma.
While a number stays the same, the representation is a different topic.
String(format: "%.6f", 12) will give 12.000000 as String.
Edit:
A Decimal is a Struct. The meaning of the numbers stays the same. Throw this in a playground.
import UIKit
let decimal = Decimal(12.0000000000)
let justAnInt = 12
let sameDecimal = decimal == Decimal(justAnInt)
See? There is no such thing as infinite 0 in math. Zero is finite. A Decimal from 12.000000 and a Decimal created from 12 are the same.
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"
Removing the decimal part of a double without converting it to Int in swift
I recommend NumberFormatter
, this example creates a reusable formatter.
let decimalFormatter : NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
private var displayValue : Double {
get {
return Double(display.text!)!
}
set {
display.text = decimalFormatter.string(for: newValue)
}
}
Getting the decimal part of a double in Swift
Without converting it to a string, you can round up to a number of decimal places like this:
let x:Double = 1234.5678
let numberOfPlaces:Double = 4.0
let powerOfTen:Double = pow(10.0, numberOfPlaces)
let targetedDecimalPlaces:Double = round((x % 1.0) * powerOfTen) / powerOfTen
Your output would be
0.5678
Only show my float number to a certain decimal place - Swift
Use a NumberFormatter
(have a look here)
let bmi:Float = (((textfieldInt! * 2.204623) * 0.5) / 1500) * textfield2Int!
let formatter = NumberFormatter()
//Set the min and max number of digits to your liking, make them equal if you want an exact number of digits
formatter.minimumFractionDigits = 1
formatter.maximumFractionDigits = 3
self.total2.text = formatter.string(from: NSNumber(value: bmi)) + " kcal"
Rounding a double value to x number of decimal places in swift
You can use Swift's round
function to accomplish this.
To round a Double
with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:
let x = 1.23556789
let y = Double(round(1000 * x) / 1000)
print(y) /// 1.236
Unlike any kind of printf(...)
or String(format: ...)
solutions, the result of this operation is still of type Double
.
EDIT:
Regarding the comments that it sometimes does not work, please read this: What Every Programmer Should Know About Floating-Point Arithmetic
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"
Related Topics
Uigesturerecognizer on Uiimageview
Prevent Deploying (Disable) Watchkit App with iOS iPhone App in Xcode
How to Center a Popoverview in Swift
Resizing a Uilabel to Accommodate Insets
In Swift How to Call Method with Parameters on Gcd Main Thread
iOS 7.0 No Code Signing Identities Found
Create a Rectangle with Just Two Rounded Corners in Swift
How to Add a 'Done' Button to Numpad Keyboard in iOS
How to I Import 3Rd Party Frameworks into Xcode Playground
Dismissmodalviewcontrolleranimated Deprecated
View with Continuous Scroll; Both Horizontal and Vertical
How to Save, Retrieve, Delete & Update My Data in Plist File in iOS
Command /Usr/Bin/Codesign Failed with Exit Code 1
Is Grouptableviewbackgroundcolor Deprecated on iOS 6
Swift - Saving Highscore Using Nsuserdefaults
How to Enable Back/Left Swipe Gesture in Uinavigationcontroller After Setting Leftbarbuttonitem