Rounding in Swift with Round()

Rounding in Swift with round()

You can do:

round(1000 * x) / 1000

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

Swift: Rounding float to nearest custom multiplier

You can use the same approach as rounding to a power of 10 here.

When you want to round to the nearest 0.1, you multiply by 10, round, then divide by 10. When you want to round to the nearest 0.01, you multiply by 100, round, then divide by 100.

See the pattern here? The number you multiply and divide by is always 1 over the granularity!

So for the granularity of 0.25, you multiply and divide by 4:

print(round(0.3 * 4) / 4)
// or
print(round(0.3 / 0.25) * 0.25)

More generally, given a granularity: Double and a number to round x: Double, we can round it like this:

let rounded = round(x / granularity) * granularity

How to round a Double to the nearest Int in swift?

There is a round available in the Foundation library (it's actually in Darwin, but Foundation imports Darwin and most of the time you'll want to use Foundation instead of using Darwin directly).

import Foundation

users = round(users)

Running your code in a playground and then calling:

print(round(users))

Outputs:

15.0

round() always rounds up when the decimal place is >= .5 and down when it's < .5 (standard rounding). You can use floor() to force rounding down, and ceil() to force rounding up.

If you need to round to a specific place, then you multiply by pow(10.0, number of places), round, and then divide by pow(10, number of places):

Round to 2 decimal places:

let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let num = 10.12345
let rounded = round(num * multiplier) / multiplier
print(rounded)

Outputs:

10.12

Note: Due to the way floating point math works, rounded may not always be perfectly accurate. It's best to think of it more of an approximation of rounding. If you're doing this for display purposes, it's better to use string formatting to format the number rather than using math to round it.

Round Half Down in Swift

There is – as far as I can tell – no FloatingPointRoundingRule with the same behavior as Java's ROUND_HALF_DOWN, but you can get the result with a combination of rounded() and nextDown or nextUp:

func roundHalfDown(_ x: Double) -> Double {
if x >= 0 {
return x.nextDown.rounded()
} else {
return x.nextUp.rounded()
}
}

Examples:

print(roundHalfDown(2.4)) // 2.0
print(roundHalfDown(2.5)) // 2.0
print(roundHalfDown(2.6)) // 3.0

print(roundHalfDown(-2.4)) // -2.0
print(roundHalfDown(-2.5)) // -2.0
print(roundHalfDown(-2.6)) // -3.0

Or as a generic extension method, so that it can be used with all floating point types (Float, Double, CGFloat):

extension FloatingPoint {
func roundedHalfDown() -> Self {
return self >= 0 ? nextDown.rounded() : nextUp.rounded()
}
}

Examples:

print((2.4).roundedHalfDown()) // 2.0
print((2.5).roundedHalfDown()) // 2.0
print((2.6).roundedHalfDown()) // 3.0

print((-2.4).roundedHalfDown()) // -2.0
print((-2.5).roundedHalfDown()) // -2.0
print((-2.6).roundedHalfDown()) // -3.0

How can I round UP to two decimal places in Swift?

You can use NumberFormatter to get formatted number as String. Just limit number of decimal places to 2 and set roundingMode to up

let formatter = NumberFormatter()
formatter.roundingMode = .up
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let number = 164.98001
print(formatter.string(from: NSNumber(value: number)) ?? "") // 164.99

To improve your logic even more, you can set formatter's numberStyle and locale

formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_UK")
// £164.99

Your specific usage:

let string = formatter.string(from: NSNumber(value: outputvalue)) ?? ""
total.text = string

Round a digit upto two decimal place in Swift

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 = Double(String(format: "%.2f", myDouble)) // 3.14

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 :

let myDouble = 3.141
let doubleStr = Double(String(format: "%.2f", ceil(myDouble*100)/100)) // 3.15

let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"

Rounding numbers in swift

Something like this should be good?

func formatNumber (number: Double) -> String? {

let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2

let formattedNumberString = formatter.stringFromNumber(number)
return formattedNumberString?.stringByReplacingOccurrencesOfString(".00", withString: "")

}

formatNumber(3.25) // 3.25
formatNumber(3.00) // 3
formatNumber(3.25678) // 3.26


Related Topics



Leave a reply



Submit