Round a double value to x number of decimal places in Swift
In this tutorial, we will see how to round a double value to x number of decimal places in Swift.
Suppose we have a number like 1.34127538359353. Sometimes, we might want to make it shorter, like just 1.34, because we don’t need all those extra digits after the decimal point. Rounding helps us do that, it trims the number to a certain number of decimal places.
Now, follow the methods below to achieve this task.
Using round() function
We can use the round()
function to round the double value to a specific number of decimal places. This is a built-in function of Swift.
Example
import Foundation let value = 1.34127538359353 //Rounds the value of 'value' to two decimal places let roundedValue = round(100 * value) / 100 print(roundedValue)
In the above code, the 100 * value
will multiply the original value by 100. So, the result will be the 134.127538359.
The round(100 * value)
will round the result of the multiplication to the nearest integer. It will round 134.127538359 to 134.
Then, I have divided it by 100
to round the number to two decimal places.
Output:
1.34
Using String Formatting
We can also use string formatting to round a double value to a specific number of decimal places.
Example
import Foundation let value = 1.34127538359353 //To round the number to two decimal places and convert it to a string let roundedValue = String(format: "%.3f", value) print(roundedValue)
In the above program, the String(format: "%.3f", value)
will format the value
with three decimal places using the “%.3f
” format specifier.
The “f” stands for “floating point” (decimal) number.
Output:
1.341
Using NumberFormatter
Swift provides a built-in class called NumberFormatter
, we can use this class to format numbers to a specific number of decimal places.
Example
import Foundation let value = 1.34127538359353 let formatter = NumberFormatter() formatter.maximumFractionDigits = 4 if let roundedValue = formatter.string(for: value) { print(roundedValue) }
In the above code, I have applied the NumberFormatter
to format numbers.
The maximumFractionDigits
property is set to 4 to limit the number of decimal places.
Then, I have used the string(for:)
method to convert the double value into a formatted string.
Output:
1.3413
Using the truncatingRemainder
We can also use the truncatingRemainder(dividingBy:)
method to round the double value to a specific number of decimal places.
Example
let value = 1.34127538359353 let roundedValue = (value * 100).truncatingRemainder(dividingBy: 1) == 0 ? value : (value * 100).rounded() / 100 print(roundedValue)
In the above code, the (value * 100).truncatingRemainder(dividingBy: 1) == 0
will check if there are no decimal places.
If there are no decimal places, it will return the original value. Otherwise, it will round the value to two decimal places.
Output:
1.34
Leave a Reply