【Swift】少数の丸め方あれこれ - rounded()

こんなにあったのですか。


5.2
.rounded() 5.0
.rounded(.down) 5.0
.rounded(.up) 6.0
.rounded(.towardZero) 5.0
.rounded(.awayFromZero) 6.0
.rounded(.toNearestOrEven) 5.0
.rounded(.toNearestOrAwayFromZero) 5.0

5.5
.rounded() 6.0
.rounded(.down) 5.0
.rounded(.up) 6.0
.rounded(.towardZero) 5.0
.rounded(.awayFromZero) 6.0
.rounded(.toNearestOrEven) 6.0
.rounded(.toNearestOrAwayFromZero) 6.0

-5.2
.rounded() -5.0
.rounded(.down) -6.0
.rounded(.up) -5.0
.rounded(.towardZero) -5.0
.rounded(.awayFromZero) -6.0
.rounded(.toNearestOrEven) -5.0
.rounded(.toNearestOrAwayFromZero) -5.0

-5.5
.rounded() -6.0
.rounded(.down) -6.0
.rounded(.up) -5.0
.rounded(.towardZero) -5.0
.rounded(.awayFromZero) -6.0
.rounded(.toNearestOrEven) -6.0
.rounded(.toNearestOrAwayFromZero) -6.0

0.51
.rounded() 1.0
.rounded(.down) 0.0
.rounded(.up) 1.0
.rounded(.towardZero) 0.0
.rounded(.awayFromZero) 1.0
.rounded(.toNearestOrEven) 1.0
.rounded(.toNearestOrAwayFromZero) 1.0

0.0
.rounded() 0.0
.rounded(.down) 0.0
.rounded(.up) 0.0
.rounded(.towardZero) 0.0
.rounded(.awayFromZero) 0.0
.rounded(.toNearestOrEven) 0.0
.rounded(.toNearestOrAwayFromZero) 0.0

0.03
.rounded() 0.0
.rounded(.down) 0.0
.rounded(.up) 1.0
.rounded(.towardZero) 0.0
.rounded(.awayFromZero) 1.0
.rounded(.toNearestOrEven) 0.0
.rounded(.toNearestOrAwayFromZero) 0.0

1.001
.rounded() 1.0
.rounded(.down) 1.0
.rounded(.up) 2.0
.rounded(.towardZero) 1.0
.rounded(.awayFromZero) 2.0
.rounded(.toNearestOrEven) 1.0
.rounded(.toNearestOrAwayFromZero) 1.0

👉 rounded(_:) | Apple Developer Documentation hatena-bookmark
👉 round() | Apple Developer Documentation hatena-bookmark
👉 FloatingPointRoundingRule | Apple Developer Documentation hatena-bookmark

 

🧑‍💻 チャートにしてみる

視覚化してみると全然ちげえ !



 

🧑‍💻 まとめ

僕たちが日頃使っている四捨五入は、


.rounded()

で、


.rounded(.toNearestOrAwayFromZero)

のことと同じで、

「schoolbook rounding (教科書丸め)」

と呼ばれているようです。

「bankers rounding (銀行丸め)」

とか、要領よく出来てるんですね !

👉 端数処理 - Wikipedia hatena-bookmark

ちなみに「四捨五入」って多すぎ。

👉 Rounding a double value to x number of decimal places in swift - Stack Overflow hatena-bookmark



関連ワード:  appleiOSiPhonemacmacOSSwiftSwiftUI今さら聞けない便利な設定初心者開発