LoginSignup
3
1

More than 3 years have passed since last update.

Swiftで割合の計算をしようとしたら結構はまったのでメモ

起きたエラー

割合の計算をしようとしたら、

let int1: Int = 3
let int2: Int = 10
print("期待する値:0.3", "結果:", int1 / int2 * 100)

// 結果
// 期待する値:30% 結果: 0%

となり、小数点以下の値が表示されなかった。

解決方法

Double型またはFloat型を使う。

let double1: Double = 3
let double2: Double = 10
print("期待する値:0.3", "結果:", double1 / double2)
// => 期待する値:0.3 結果: 0.3

let float1: Float = 3
let float2: Float = 10
print("期待する値:0.3", "結果:", float1 / float2)
// => 期待する値:0.3 結果: 0.3

こんな感じで期待する値を取得することが出来た。

そもそもintegerとはTechTermsによると

An integer is a whole number (not a fraction) that can be positive, negative, or zero.

と定義されており、少数ではない数(整数)事を表すが分かる。なのでInt(Integer)型で小数が関わる数字を計算すると、計算結果の整数の部分である0だけが表示され、期待された値が帰ってこなかった。

整数とは

ちなみに整数の定義は

おおざっぱな解釈としては「小数でも分数でもない数」のこと。1、2、3、4、という数の連なり(自然数)と、0(ゼロ)、および負数(-1、-2、-3、-4、)を総称した言い方。
らしい。

DoubleとFloat

Swiftでは小数扱う型として主にDouble型とFloat型が提供されていることが分かったが、どうやって使い分けたらいいか分からなかったので、調べてみた。

Swiftのドキュメントによると

Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits. The appropriate floating-point type to use depends on the nature and range of values you need to work with in your code. In situations where either type would be appropriate, Double is preferred.

と書かれている。意訳すると、

Double型は小数15桁まで、Float型は小数6桁まで表すことができる。どちらの型が適切かどうかは状況によって異なるが、どちらでもOKな場合はDouble型が推奨です。

と書かれている。

感想

「integer = 整数 = 小数でも分数でもない数」という認識が頭にあったら15分も悩む必要がなかったので、
卍 英語と数学は大事 卍

参考文献

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1