2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Jestでテストを書く時に注意した小数点の計算について

Posted at

現在Jestを勉強していますが、テストを記載する際に気をつけないといけないことがあると学んだので備忘録として残します。

小数点の計算には気をつける

sum.ts
export const sum = (a: number, b: number) => a + b;
sum.test.ts
test('0.1 + 0.2 returns 3', () => {
  expect(0.1 + 0.2).toBe(3)
})

// 結果
Expected: 3
Received: 0.30000000000000004

      6 |
      7 | test('0.1 + 0.2 returns 3', () => {
>  8 |   expect(0.1+0.2).toBe(3)
          |                   ^
   9 | })
  10 |

理由は、Numberが「IEEE 754 倍精度浮動小数点数」のためです。
とかいたもののピンと自身もピンときていません…笑

「IEEE 754 倍精度浮動小数点数」とは1の位より下も2進数で表します。
10進数の0.2は有限小数、2進数では0.0011で循環小数になります。
BigIntは整数のみを扱うことができるためこの問題は発生しない。
Numberを利用する場合は整数のみを利用するかライブラリを使う必要がある。

【まとめ】Jestでの小数点の計算について

小数点を計算する際の注意点はJestというよりは、Numberの仕様の話を知っているかだと思います。
これまで気にしなかったことが多いですが、テストを書くことによってJavaScriptの仕様や関数の振る舞いの詳細な部分にまで知識が及ばないと正しいテストコードが書けないのだと知りました。

JavaScriptの仕様を把握していきたいです。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?