Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

swift - Round Double to closest 10

I would like to round a Double to the closest multiple of 10.

For example if the number is 8.0 then round to 10. If the number is 2.0 round it to 0.

How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...