오랜만에 포스트를 남겨야지하다가 이건 남겨도 괜찮겠다 싶어서 남깁니다.
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
돈자리수표시.swift
GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
반응형
'iOS > swift' 카테고리의 다른 글
배열을 그룹별로 분리하기 Dictionary(grouping:, by:) (0) | 2022.04.22 |
---|---|
collectionView의 scrollToItem이 동작하지 않는다. (0) | 2022.03.14 |
비밀번호용 텍스트필드가 가려지면서 도중 수정이 가능하려면... (0) | 2022.02.19 |
CollectionView ScrollToItem Error, 이전에는 잘됐는데! (0) | 2022.02.07 |
메모. iOS 시작화면 애니메이션 - 카메라 조리개 (0) | 2022.01.24 |