LoginSignup
0
0

More than 1 year has passed since last update.

100で割ってから100で掛けると元の数字に戻らないJSの数値の例

Last updated at Posted at 2021-06-04

最近まで「JSの数値演算は誤差が...」的な話は自分には縁遠かったですが。。。

TL;DR;

//左=元の数、右= 元の100で割ってから100掛けた結果(100以下の数の場合)
[ 7, 7.000000000000001 ]
[ 14, 14.000000000000002 ]
[ 28, 28.000000000000004 ]
[ 29, 28.999999999999996 ]
[ 55, 55.00000000000001 ]
[ 56, 56.00000000000001 ]
[ 57, 56.99999999999999 ]
[ 58, 57.99999999999999 ]

確認方法

// 100で割って100で掛けると少数になる数を抽出
[...Array(100).keys()]
  .map(x => x++)
  .map(x => [x, (x / 100) * 100])
  .filter(x => !Number.isInteger(x[1]))
  .forEach(x => console.log(x));

対策

元の数より大きい場合、小さいい場合、.000000000000001大きい場合、0.000000000000004小さい場合、等々まちまち。少数点への演算は、Math.floor() , Math.ceil()の内部でのみ行うくらいしか思いつかず。

0
0
1

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