Round Down in Swift

Round down in swift

Just replace round with floor!

How would you round up or down a Float to nearest even numbered integer in Swift 3?

If you want to round to the nearest even number, divide by 2, round and then multiply by 2:

let rounded = Int(round(value / 2.0)) * 2

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

Round a double down to one decimal place (dropping decimal places)

Use the function trunc() (which stands for truncate) which will chop away the decimal portion without rounding. Specifically, multiply the Double value by 10, truncate it, then divide by 10 again. Then, to display using 1 decimal place, use String(format:):

let aDouble = 1.15
let truncated = trunc(aDouble * 10) / 10
let string = String(format: "%.1f", truncated
print(string)

(displays "1.1")

or, to process an entire array of sample values:

let floats = stride(from: 1.099, to: 2.0, by: 0.1)

let truncs = floats
.map { trunc($0 * 10) / 10 }
.map { String(format: "%.1f", $0) }

let beforeAndAfter = zip(floats, truncs)
.map { (float: $0.0, truncString: $0.1)}

beforeAndAfter.forEach { print(String(format: "%.3f truncated to 1 place is %@", $0.0, $0.1)) }

Outputs:

1.099 truncated to 1 place is 1.0
1.199 truncated to 1 place is 1.1
1.299 truncated to 1 place is 1.2
1.399 truncated to 1 place is 1.3
1.499 truncated to 1 place is 1.4
1.599 truncated to 1 place is 1.5
1.699 truncated to 1 place is 1.6
1.799 truncated to 1 place is 1.7
1.899 truncated to 1 place is 1.8
1.999 truncated to 1 place is 1.9

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

Make Int round off to nearest value

For nonnegative integers, the following function gives
the desired result in pure integer arithmetic :

func divideAndRound(numerator: Int, _ denominator: Int) -> Int {
return (2 * numerator + denominator)/(2 * denominator)
}

Examples:

print(20000.0/7000.0) // 2.85714285714286
print(divideAndRound(20000, 7000)) // 3 (rounded up)

print(10000.0/7000.0) // 1.42857142857143
print(divideAndRound(10000, 7000)) // 1 (rounded down)

The idea is that

 a   1   2 * a + b
- + - = ---------
b 2 2 * b

And here is a possible implementation for arbitrarily signed
integers which also does not overflow:

func divideAndRound(num: Int, _ den: Int) -> Int {
return num / den + (num % den) / (den / 2 + den % 2)
}

(Based on @user3441734's updated solution, so we have a reference
cycle between our answers now :)

There is also a ldiv function which computes both quotient
and remainder of a division, so the last function could also be
implemented as

func divideAndRound(num: Int, _ den: Int) -> Int {
let div = ldiv(num, den)
let div2 = ldiv(den, 2)
return div.quot + div.rem / (div2.quot + div2.rem)
}

(I did not test which version is faster.)

How to round UP to the next quarter?

You can use ceil() instead to force your number to round up.

Round up to the next quarter:

let someDouble: Double = 34.26
let doubleCeiledUp = ceil(someDouble * 4) / 4 //prints as 34.5

If you wanted to force round down, you can use floor().

Round Integer Numbers in Swift

If you want to round down to a multiple of 100 then you can
do that with (as @vadian said in a comment):

let amount = 1397968
let rounded = amount/100 * 100
print(rounded) // 1397900

This works because integer division truncates the result
towards zero: amount/100 evaluates to 13979, and multiplying
by 100 again gives 1397900.

But you asked for the nearest multiple of 100 for a given integer,
and that can be done with a small modification:

let amount = 1397968
let rounded = (amount + 50)/100 * 100
print(rounded) // 1398000

for nonnegative integers. If you have both positive and negative
values then @shallowThought's answer is probably the easiest
way to go. But it can be done with pure integer arithmetic as well
(using the approach from Make Int round off to nearest value):

func roundToHundreds(_ value: Int) -> Int {
return value/100 * 100 + (value % 100)/50 * 100
}

roundToHundreds(123) // 100
roundToHundreds(188) // 200

roundToHundreds(-123) // -100
roundToHundreds(-188) // -200

This works for the full range of Int:

roundToHundreds(Int.max) // 9223372036854775800
roundToHundreds(Int.min) // -9223372036854775800


Related Topics



Leave a reply



Submit