Round double value with n number decimal places in the swift example

It is a common requirement to display prices and orders with a limit of 3 decimal places.

This tutorial explains how to round double values to limit decimal places.

There are multiple ways we can limit decimal places.

For example, If the input is 123.456789, the output is 123.456.

How to round double values to limit decimal or fraction parts in Swift?

Following are ways to round double fractional parts

  • NumberFormatter class

NumberFormatter class provides to format and rounding the numbers.

It is mainly used to add grouping and limit and rounding fractional parts of numeric types Configure NumberFormatter class to the below values

  • numberStyle to NumberFormatter.Style.decimal
  • roundingMode to NumberFormatter.RoundingMode.floor that converts the number to less than give decimal parts
  • maximumFractionDigits to integer to limit decimal parts.

Finally, call the string method with from values and returns the rounded numbers in the Optional object.

Here is an example code

import Foundation

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.roundingMode = NumberFormatter.RoundingMode.floor
numberFormatter.maximumFractionDigits = 2

let result1 = numberFormatter.string(from: 123456.17213)
let result2 = numberFormatter.string(from: 090.17872134)
print(String(describing: result1))
print(String(describing: result2))

Output:

Optional("123,456.17")
Optional("90.17")

using String Format

Another way using the String Format method.

It is a simple way of using Foundation String where String is a wrapper class for NSString. %.3f limit the value to 3 digits. Here is an example code


import Foundation

let value: Double = 3123.11231231231231
print(String(format:"%.3f", value))

Output:

3123.112

NSDecimalNumber rounding class

NSDecimalNumber has a rounding method that returns rounding of a decimal part of a number

Here is a syntax

func rounding(accordingToBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber

NSDecimalNumberBehaviors is a parameter to the rounding method. Which can be created using NSDecimalNumberHandler with scale parameter.

Here is an example

import Foundation

let limitFranction: Int16 = 2


let handler = NSDecimalNumberHandler(roundingMode: .plain, scale: limitFranction, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)

let result = NSDecimalNumber(value: 3123.11231231231231).rounding(accordingToBehavior: handler)

print(result)

Output:

3123.11