[SOLVED] Trying to combine a number and variable in Swift

Issue

I am a newbie trying hard to create 0.2 from combining a a number and a variable together. But I think I have it all backwards somehow. can anyone help?

//turns a string of ‘20%’ into ‘2’.

let tipPercent = tip.prefix(1)

//turns the string into a Int of ‘2’

let tipPercent1: Int = Int(tipPercent) ?? 0 

//So now I want to combine the 0. with the variable tipPercent1. this will create ‘0.2’

let twentyTipamount = (billamount * 0.tipPercent1) + billamount

Solution

It seems like you just want to parse a percent string into a number. You should use a NumberFormatter.

let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en-US_POSIX")
// or whatever other locale that your tip is written in

numberFormatter.numberStyle = .percent
// if the tip cannot be parsed, use 0 as the default
let tipRate = numberFormatter.number(from: tip)?.doubleValue ?? 0
// or you can do something else:
// guard let tipRate = numberFormatter.number(from: tip)?.doubleValue else { ... }

// calculate the amount after tips
let totalAmount = billamount * (1 + tipRate)

Answered By – Sweeper

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

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