오랜만에 포스트를 남겨야지하다가 이건 남겨도 괜찮겠다 싶어서 남깁니다.
func moneyPlaceHolder(money: Int) -> String {
guard money >= 0 else { return "" }
let moneyString = String(money)
let moneyCount = moneyString.count
let insertPlaceCount = 3
if moneyCount <= insertPlaceCount {
return moneyString
}
let index0: String.Index = moneyString.startIndex
var resultString = ""
var loopIndex = 0
for i in (0 ..< moneyCount).reversed() {
resultString += String(moneyString[moneyString.index(index0, offsetBy: i)])
loopIndex += 1
if loopIndex >= insertPlaceCount {
resultString += ","
loopIndex = 0
}
}
return String(resultString.reversed())
}
테스트 값:
print(moneyPlaceHolder(money: 1355500))
print(moneyPlaceHolder(money: 500))
print(moneyPlaceHolder(money: 1500))
print(moneyPlaceHolder(money: 034))
print(moneyPlaceHolder(money: 65))
print(moneyPlaceHolder(money: 0))
print(moneyPlaceHolder(money: 1))
print(moneyPlaceHolder(money: -30))
/**
result
1,355,500
500
1,500
34
65
0
1
*/
더 짧거나 효율좋게 할 수 있는 방법이 있으면 좋겠네요.
https://gist.github.com/wiwi-git/646b628dec8a7ed940c3d0cc885017fd