Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

Olive Study Room

[Swift] 소수점 다루기 본문

Coding/iOS

[Swift] 소수점 다루기

Olive Dev 2021. 6. 23. 13:54

* 필요 지식

더보기

Int형과 Double형은 상호간에 나눌 수 없다. (당연함..)

 

나누려고 했을 때 0으로 출력되는 경우가 있는데 그 이유는

Int/Int -> Int

Double/Double -> Double 이기 때문에

1(Int) / 5(Int) -> 0.2이렇게 출력되는게 아니라

1(Int) / 5(Int) -> 0(Int) 이렇게 출력된다.

 

그렇기 때문에 나누는 수 중 Double형이 있다면 다른 모든 변수도 Double로 형변환해주어야 한다.


 

String.format(), NumberFormatter, ceil, floor, round

 

 

* 설명된 모든 경우는 Foundation 프레임워크 내에 있다.

import Foundation

 

 

1. 기본형

- ceil()

소수점 이하를 버리고 정수에 +1

- floor()

소수점 이하를 버림

- round()

소수점 이하를 반올림

import Foundation
print(ceil(3.14159265359)) // 4.0
print(floor(3.14159265359)) // 3.0
print(floor(3.66666666)) // 3.0
print(round(3.14159265359)) // 3.0
print(round(3.66666666)) // 4.0

* 특정 자릿수에서 자르기

print(floor(3.14159265359 * 1000)/1000) // 3.141

* 특정 자릿수에서 반올림

print(round(3.14159265359 * 1000)/1000) // 3.142

 

2. 원하는 자리 수까지 표시하기

- String(format: String, arguments)

print(String(format: "%.2f", 3.14159265359 )) // 3.14
print(String(format: "%.2f", 3.1 )) // 3.10

 

- NumberFormatter

숫자 값과 해당 텍스트 표현 사이를 변환하는 formatter

Declaration

class NumberFormatter : Formatter

 

사용 방법 & 메소드

 

import Foundation
let num = 3.14159265359
let numberFormatter = NumberFormatter()

numberFormatter.minimumSignificantDigits = 4  // 나오길 원하는 자릿수 3.14 -> Optional("3.140")
numberFormatter.maximumSignificantDigits = 4 // 자르길 원하는 자릿수 3.14159265359 -> Optional("3.142")
numberFormatter.numberStyle = .decimal // 세 자리마자 컴마 찍음 314159265359 -> Optional("314,159,265,359")

numberFormatter.roundingMode = .floor // 3.14159265359 -> Optional("3.141")
numberFormatter.roundingMode = .ceiling // 3.14159265359-> Optional("3.142")
let result = numberFormatter.string(for: num)
print(result)

이 외에도 많은 메소드들이 있다. 

 

 

 

 

 

'Coding > iOS' 카테고리의 다른 글

[iOS] Cocoa touch(UIKit, Foundation)  (0) 2021.10.10
[Swift, iOS] Swift 개요와 개발환경  (0) 2021.10.07
[Swift] Map VS compactMap VS flatMap  (0) 2021.06.23
[Swift] Control Flow  (0) 2021.06.17
[Swift] 고차함수(map, filter, reduce)  (0) 2021.06.07
Comments