↑クリックして拡大
↑クリックして拡大
↑クリックして拡大
↑クリックして拡大

頭痛が減ったので共有です!

rebuild.fmを応援しています!

HOME > 四捨五入

四捨五入

四捨五入する必要があったのですが本サイトで特化して記載していたことがなかったので記事にしてみました。 必要なのは、切り捨て、切り上げ、四捨五入、です。

参考:Rounding in Swift with round()
参考:How to round a Double to the nearest Int in swift?
参考:Convert Float to Int in Swift
参考:swiftで質問があります。Double型の変数の小数の四捨五入を行うにはどうすれば良いのでしょうか?
参考:Swift:浮動小数点の盲点

やってみた

そのままですが、それぞれの関数を実施します。


//切り捨てfloor
//切り上げceil
//四捨五入round

var test = 1.2345
print (floor(test)); // ->1.0
print (floor(ceil)); // ->2.0
print (floor(round)); // ->1.0

カスタマイズ

小数点第二以下の処理の場合先に適切な桁数分10を掛けて、処理後に割り算して出力します。


//切り捨てfloor
//切り上げceil
//四捨五入round

var test = 1.2345
test = test * 10; // -> 12.345

print (floor(test)); // ->12.0
print (floor(ceil)); // ->13.0
print (floor(round)); // ->12.0

print (floor(test)/10); // ->1.2
print (floor(ceil)/10); // ->1.3
print (floor(round)/10); // ->1.2

まとめ

小数点の切り上げ切り捨ては小学校時代を思い出します。。。

↓こんな記事もありますよ!

2021-05-14 14:21:41

The pitfalls of Filetransfer in watchconnectivity on WatchOS. And how to avoid.

AppleWatch it succeeds with the actual machine, but if it is a simulator, it will fail、、、 When I...
2021-05-06 14:04:37

Line's animation stamp production pitfalls 、、、 failure story

I tried to make a LINE sticker during Golden Week. I made it and applied, but it was different f...
2021-04-22 14:54:53

Cool carousel carefully selected 3 points! Astringent image slider using WebGL.

I was on a trip to find a cool slider yesterday. It's simple, easy to use, and has a good de...
このエントリーをはてなブックマークに追加
右側のFacebookのLikeをクリック頂けると記事更新の際に通知されますので宜しければご利用下さい!