BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Vat amount calculate

Forums > SwiftUI

hi everyone , I tried this code for calculate vat amount because not all items have a vat.

private var vatAmount1: Double {

        itemsData.items.reduce(0.0) { partialResult, item in

            if item.vat > 0 {

                let vat = item.price / 100 * item.vat

                return partialResult + vat


            return partialResult



item.price = 2.200 included vat item.vat = 10

The result from that code is 0.220 , but the correct result is 0.200 , How to solve that ?

Thanks in Advance


Hi, It is not really clear what are you trying to achieve at least for me. Do you want to get aggregate amout for all items, or to add VAT to particular item?

if you need to calculate the amount for VAT use this logic.

You have gross amount with VAT included so calculate first NET amount. Then from GROSS amount deduct NET amount and you will get VAT amount.

NET = GROSS / (1 + VAT/100)

VAT amount = GROSS - NET

let netAmount = item.price / (1 + item.vat/100)
let vatAmount = item.price - netAmount


Thanks @ygeras


Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.