0

I am new in Swift. I am trying to make a budget application. This app have a Calculator like keyboard. My idea is when users enter the money app will automatically add a decimal place for users.

For example, if you type 1230 it will give you 12.30 and type 123 it will display 1.23

I wrote a couple lines of code down below. The problem is it only can add decimal point after first digit it won't go backwards when you give more digits. It only can display as X.XXXXX

I tried solve this problem with String.index(maybe increase index?) and NSNumber/NSString format. But I don't know this is the right direction or not.

    let number = sender.currentTitle!
    let i: String = displayPayment.text!

    if (displayPayment.text?.contains("."))!{

        displayPayment.text = i == "0" ? number : displayPayment.text! + number

    }
    else {

    displayPayment.text = i == "0" ? number : displayPayment.text! + "." + number

    }
  • Easiest solution is to have user enter decimal because it might be annoying to enter 12300 instead of just 123 for $123.00. So they could type 123 and it would assume decimal at 123.00. – Will Boland Jan 23 '17 at 15:54
  • possible duplicate of http://stackoverflow.com/a/29783546/2303865 – Leo Dabus Jan 23 '17 at 15:59

1 Answers1

0

Indexing Strings in Swift is not as "straightforward" as many would like, simply due to how Strings are represented internally. If you just want to add a . at before the second to last position of the user input you could do it like this:

let amount = "1230"
var result = amount

if amount.characters.count >= 2 {
    let index = amount.index(amount.endIndex, offsetBy: -2) 
    result = amount[amount.startIndex..<index] + "." + amount[index..<amount.endIndex]
} else {
    result = "0.0\(amount)"
}

So for the input of 1230 result will be 12.30. Now You might want to adjust this depending on your specific needs. For example, if the user inputs 30 this code would result in .30 (this might or might not be what you want).

Keiwan
  • 8,031
  • 5
  • 36
  • 49