Bibi's DevLog ๐Ÿค“๐ŸŽ

[Swift] ์‹ค์ˆ˜๋ฅผ ์†Œ์ˆ˜์  n์งธ ์ž๋ฆฌ๊นŒ์ง€ ์ถœ๋ ฅํ•˜๊ธฐ - round, String(format:_:) ๋ณธ๋ฌธ

๐Ÿ“ฑ๐ŸŽ iOS/๐Ÿ•Š Swift

[Swift] ์‹ค์ˆ˜๋ฅผ ์†Œ์ˆ˜์  n์งธ ์ž๋ฆฌ๊นŒ์ง€ ์ถœ๋ ฅํ•˜๊ธฐ - round, String(format:_:)

๋น„๋น„ bibi 2022. 11. 28. 15:57

Rounding a double value to x number of decimal places in swift

์†Œ์ˆ˜์  n์งธ ์ž๋ฆฌ๊นŒ์ง€ ์ถœ๋ ฅํ•˜๊ธฐ

1. round() ํ™œ์šฉ

let x = 1.23556789
let y = Double(round(1000 * x) / 1000)
print(y) /// 1.236

์˜ˆ๋ฅผ ๋“ค์–ด ์†Œ์ˆ˜์  3์งธ์ž๋ฆฌ๊นŒ์ง€ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค๋ฉด,

  • ์›๋ž˜ ๊ฐ’์— 1000์„ ๊ณฑํ•œ๋‹ค
  • ๋ฐ˜์˜ฌ๋ฆผ ์ฒ˜๋ฆฌํ•œ๋‹ค
  • ๋‹ค์‹œ 1000์œผ๋กœ ๋‚˜๋ˆˆ๋‹ค

์ด๋ ‡๊ฒŒ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.

์ž์ฃผ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ์ต์Šคํ…์…˜์œผ๋กœ๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

2. String(format:_:) ํ™œ์šฉ

let x = 1.23556789
print(String(format: "%.3f", x)) // 1.236

String(format:_:) ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ์†Œ์ˆ˜์  n์งธ ์ž๋ฆฌ๊นŒ์ง€ ๋ฌธ์ž์—ด๋กœ ์ถœ๋ ฅํ•œ๋‹ค.

  • ๋‹จ์ 
    • ํƒ€์ž…์ด ๋ฌธ์ž์—ด์ด ๋œ๋‹ค.
    • import Foundation ์ด ํ•„์š”ํ•˜๋‹ค.
  • ์žฅ์ 
    • ๊ฐ’ ์ž์ฒด๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š๊ณ  ๋‹จ์ˆœ ์ถœ๋ ฅ ์šฉ๋„๋กœ ์‚ฌ์šฉํ•  ๋•Œ
    • ๋ฐ˜์˜ฌ๋ฆผ ํ›„ ์†Œ์ˆ˜์  ๋งจ ๋ ์ž๋ฆฌ๊ฐ€ 0์ด ๋˜์—ˆ์„ ๋•Œ, 0์„ ํฌํ•จํ•ด ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค๋ฉด ์ด ๋ฉ”์„œ๋“œ๋ฅผ ์“ฐ๋Š” ๊ฒŒ ์ข‹๋‹ค.
let e = 2.71827876984127 // 10์งธ ์ž๋ฆฌ์—์„œ ๋ฐ˜์˜ฌ๋ฆผ
print(round(e * 100_000_000) / 100_000_000) // 2.71827877
print(String(format:"%.9f", e)) // 2.718278770