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
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
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"
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's Decimal precision issue
NSDecimalNumber
(and its overlay type Decimal
) can represent
... any number that can be expressed as
mantissa x 10^exponent
wheremantissa
is a decimal integer up to 38 digits long, andexponent
is an integer from –128 through 127.
So decimal fractions (with up to 38 decimal digits) can be represented
exactly, but not arbitrary numbers. In particular 1/24 = 0.416666666...
has infinitely many decimal digits (a repeating decimal) and cannot be
represented exactly as a Decimal
.
Also there is no precision difference between Decimal
and NSDecimalNumber
. That becomes apparent if we print the difference
between the actual result and the "theoretical result":
let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24
print(decResult - dec1)
// -0.00000000000000000000000000000000000016
let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)
print(dnResult.subtracting(dn1))
// -0.00000000000000000000000000000000000016
Make a float only show two decimal places
It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.
E.g.:
NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
%.02f
tells the formatter that you will be formatting a float (%f
) and, that should be rounded to two places, and should be padded with 0
s.
E.g.:
%f = 25.000000
%.f = 25
%.02f = 25.00
Rounding a double to 2 decimal places in Swift, XCode 12
You could do it directly inside Text
with the help of string interpolation:
struct ContentView: View {
let decimalNumber = 12.939010
var body: some View {
Text("\(decimalNumber, specifier: "%.2f")")//displays 12.94
}
}
How to truncate decimals to x places in Swift
You can tidy this up even more by making it an extension of Double
:
extension Double {
func truncate(places : Int)-> Double {
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}
}
You use it like this:
var num = 1.23456789
// return the number truncated to 2 places
print(num.truncate(places: 2))
// return the number truncated to 6 places
print(num.truncate(places: 6))
Related Topics
Try, Try! & Try? What's the Difference, and When to Use Each
Check If Key Exists in Dictionary of Type [Type:Type]
Should Conditional Compilation Be Used to Cope With Difference in Cgfloat on Different Architectures
In Swift 3, What Is a Way to Compare Two Closures
Expected to Decode Array<Any> But Found a Dictionary Instead
How to Use Array.Filter to Filter a Class Object Based on a Property
Alamofire Asynchronous Completionhandler For Json Request
Array Element Cannot Be Bridged to Objective-C
Swift: How to Detect Linear Type Barcodes
Convert a Swift Array of String to a to a C String Array Pointer
Uiapplication.Shared.Delegate Equivalent for Scenedelegate Xcode11
Do Swift Inner Classes Have Access to Self of Outer Class