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 "%.nf" 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 Fletcher29 Sep 2023
Setting up an ionic app
Recently a client handed me code that runs an app through iOS and Android.  No details about whether native or otherwise.  Once I had the opportunity to crawl through the code, definitely not native.  Typescript, Angular, Cordova... etc.Glancing at the modification dates, the last...
Andrew Fletcher02 Aug 2023
Android Studio error when running app through emulator
Only a month ago, running an app through the Android Studio emulator was running fine.  Now I'm warmly greeted byError Installation did not succeed. The application could not be installed: INSTALL_PARSE_FAILED_NO_CERTIFICATESThe complete error is Launching '{project}' on Pixel 5 API...
Andrew Fletcher22 Aug 2022
Android releasing app issues
Warning from Google Play Store when uploading an App You must complete the advertising ID declaration before you can release an app that targets Android 13 (API 33). We'll use this declaration to provide safeguards in Play Console to accommodate changes to advertising ID in Android 13. Apps...