How to input currency format on a text field (from right to left) using Swift?

前端 未结 9 1054
甜味超标
甜味超标 2020-11-22 01:57

I have a number let’s say 0.00.

  • When the user taps 1. We should have 0.01
  • When the user taps 2. We should display 0.
9条回答
  •  别那么骄傲
    2020-11-22 02:45

    Just for fun: copied Thomas's answer (full credits -and points- to him please) into a file to run as a Swift 4.1 script (with minor fixes):

    dotnum.swift:

    #!/usr/bin/swift
    
    struct DotNum {
        private var fraction:String = ""
        private var intval:String = ""
        init() {}
        mutating func enter(_ s:String) {
            if fraction.count < 2 {
              fraction = s + fraction
            } else {
              intval = s + intval
            }
        }
        private var sFract:String {
            if fraction.count == 0 { return "00" }
            if fraction.count == 1 { return "0\(fraction)" }
            return fraction
        }
        var stringVal:String {
            if intval == ""  { return "0.\(sFract)" }
            return "\(intval).\(sFract)"
        }
    }
    
    var val = DotNum()
    val.enter("1")
    print(val.stringVal)
    val.enter("2")
    print(val.stringVal)
    val.enter("3")
    print(val.stringVal)
    val.enter("4")
    print(val.stringVal)
    

    Then run it in a terminal:

    $ chmod +x dotnum.swift
    $ ./dotnum.swift
    0.01
    0.21
    3.21
    43.21
    

提交回复
热议问题