How to calculate tax in Swift

When performing any type of financial calculation, it is best not to use floating point numbers. Performing arithmetic in base 10 will allow you to avoid unexpected errors in how floats represent some decimals. Fortunately, Apple provides the NSDecimalNumber class to handle calculations using base 10 arithmetic.

Tax calculation example:

let price: Int = 15 // $15
let priceDecimalNumber = NSDecimalNumber(integer: price)

let taxPercentage = NSDecimalNumber(string: "0.09") // 9%

let tax = priceDecimalNumber.decimalNumberByMultiplyingBy(taxPercentage)
let taxDouble = tax.doubleValue // Retrieve the double value

More information about floating point arithmetic:

Subscribe to the newsletter to stay up to date with new articles.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see