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

Related articles

Andrew Fletcher16 Aug 2022

How to handle a lost KeyStore password in Android?

If you have a situation where either you have forgotten a Keystore password or change of developers and the password wasn't sent across.... what to do?  However, your app lives on and needs to be updated!   Possible solutions This is a great starting point....
Andrew Fletcher01 Aug 2022

Ionic - Capacitor config​

Initialise your Capacitor config​ To initialise Capacitor use the CLI questionnaire: npx cap init On executing the above command, you will be prompted to answer a few questions for your app such as your app's name and the package ID. [?] What is the name of your app? This should...