round a number to the nearest tenth in swift

To round a number to the nearest tenth in Swift, you can make use of the round() function and number formatting techniques.

main.swift
let value = 3.4567
let roundedValue = round(value * 10) / 10
print(roundedValue) // prints 3.5
95 chars
4 lines

In the code above, we multiply the original value by 10, rounding it to the nearest integer, and then divide it back by 10 to get the final rounded value.

Another option is to use the String(format: "%.1f", value) method to format the number to have one decimal place, which automatically rounds it to the nearest tenth.

main.swift
let value = 3.4567
let formattedValue = String(format: "%.1f", value)
print(formattedValue) // prints 3.5
106 chars
4 lines

Both of these methods will round a number to the nearest tenth in Swift.

gistlibby LogSnag