Making Large Numbers Readable in Swift

When writing large numbers on paper, it’s common to use commas to make the number easier to understand. For example, you could write

308945025

Of course, such a number can be hard to read so when writing such large numbers on paper, people use commas to separate every three digits like this:

308,945,025

If you need to use large numbers in a Swift program, you can’t use commas since the computer won’t recognize commas as place markers. Instead, Swift lets you use the underscore character. So if you wanted to declare a variable like this:

var distance = 308945025

You could use an underscore character in place of commas like this:

var distance = 308_945_025

Using the underscore character in large numbers is optional but can make numbers easier for people to read. Remember, given a choice between making programs easier for machines or human beings, always choose to make life easier for people.

June 14th, 2014 by
HTML Snippets Powered By : XYZScripts.com