Displaying Decimal Numbers as Strings with Format Specifiers

With most older programming languages, printing data of different types can be a nuisance since you typically have to convert everything into a string. Swift avoids this hassle by simply letting you identify data to print or store into a string using the \() symbols such as:

let number = 1.2547032

let myString = "\(number)"
print (myString)

The above code simply stores a decimal number (1.2547032) into a variable that stores Double data types. (The Double data type is assumed by Swift.) Then rather than convert that Double variable into a string, Swift just lets you store that data as a string using the \() symbols.

If you try the above code in a Swift playground, you’ll find that the print statement simply prints the string “1.2547032”.

When printing or converting decimal values into strings, you might not want to display all the decimal values. A simple way to define exactly how many values after the decimal value to display is to use a format specifier.

If you’re familiar with the C programming language, you may already know that you use a % followed by a decimal point, and then the number of decimal places you want to display, followed by the “f” letter that stands for floating point like this:

let number = 1.2547032

let modifiedNumber = String(format: "%.2f", number)

This code simply turns the number 1.2547032 into a string with two decimal places or 1.25. Then it prints the string “1.25”.

By using a format specifier to print or convert decimal values to a string, you can show as many decimal places as you wish such as two or three.

November 13th, 2017 by
HTML Snippets Powered By : XYZScripts.com