How to Round a Double to the Nearest Int in Swift

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 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

How can I round Int to nearest 10 in Swift?

You need to use round function and x % 5 == 0 check.

let values = (6...100).map({ Double($0) })

func round(_ value: Double, toNearest: Double) -> Double {
return round(value / toNearest) * toNearest
}

for x in values {
if x.truncatingRemainder(dividingBy: 5) == 0 {
print("x - \(x), y - \(Int(x / 5))")
} else {
let rounded = round(x, toNearest: 10.0)
print("x - \(x), y - \(Int(rounded / 5))")
}
}

Round Double to closest 10

You can use the round() function (which rounds a floating point number
to the nearest integral value) and apply a "scale factor" of 10:

func roundToTens(x : Double) -> Int {
return 10 * Int(round(x / 10.0))
}

Example usage:

print(roundToTens(4.9))  // 0
print(roundToTens(15.1)) // 20

In the second example, 15.1 is divided by ten (1.51), rounded (2.0),
converted to an integer (2) and multiplied by 10 again (20).

Swift 3:

func roundToTens(_ x : Double) -> Int {
return 10 * Int((x / 10.0).rounded())
}

Alternatively:

func roundToTens(_ x : Double) -> Int {
return 10 * lrint(x / 10.0)
}

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.)

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 to round double in swift to 2 places with math round

extension Double {
// Rounds the double to decimal places value
// Usage: (doubleVar).roundToPlaces(x)
// Where x is the number of places
func roundToPlaces(places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(self * divisor) / divisor
}
}

Source: Rounding a double value to x number of decimal places in swift

round double to 0.5

x = 13000 / 9000.0;

denominator = 2;
a.text = String(round(x*denominator )/denominator );

First convert 1.444 to 2.888, then round to 3.0 and then divide by 2 to get 1.5. In this case, the denominator of 0.5 is 2 (i.e. 1/2). If you want to round to nearest quarter (0.25,0.5, 0.75, 0.00), then denominator=4

I Should point out that this works perfectly if the denominator is a power of 2. If it is not, say denominator=3, then you can get weird answers like 1.99999999 instead of 2 for particular values.



Related Topics



Leave a reply



Submit