Skip to main content

Adding a floating decimal point for n number of places is quite easy to achieve.  The key to understand is the receive an outcome of a fraction the numbers need to be Double.  So Int numbers will result in a whole number product.  By way of example:

  • 80 / 3 = 26

We know that this result is incorrect.  To get the correct outcome the equation needs to be as follows:

  • 80.0 / 3.0 = 26.666666666666667

If you have a whole number - add Double to the whole number.  So write the expression as:

  • Double(80.0) / 3.0 = 26.666666666666667

let value: Double = 123.456789

let formatted = String(format: "%.3f", value)

The "%f" format string means "a floating point number," but "" will float the number to n places after the decimal point.  Therefore, "%.3f" will be a floating-point number with three digits after the decimal point. Note, Swift will automatically round the final digit as needed based on the last number.

Using the example above will show the formatted value to be 123.457