V
V
Vlad Osadchyi2019-10-30 17:12:17
PHP
Vlad Osadchyi, 2019-10-30 17:12:17

Why would in_array(1.7, range(0, 2, 0.1)) return false?

Why will it return ? And it will return Either I don’t know something in php or in mathematics php 5.6 windows 10 in_array(1.7, range(0, 2, 0.1))false
in_array(1.7, range(0, 2, 0.01))true

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2018-09-11
@Deman1

function num($amount) {
  return max( 100 * floor($amount / 100), 100);
}

examination
for($i = 0; $i < 500; $i += rand(0,90)) {
  printf("%3d -> %3d\n", $i, num($i));
}

Результат:
0 -> 100
  2 -> 100
 57 -> 100
105 -> 100
118 -> 100
166 -> 100
249 -> 200
254 -> 200
295 -> 200
307 -> 300
315 -> 300
349 -> 300
403 -> 400
437 -> 400
480 -> 400
488 -> 400

D
Daria Motorina, 2019-10-30
@VladOsadchyi

Floating point numbers do not have the precision in binary representation that they visually look like in php in decimal representation (even if you explicitly specify the number of decimal places). You can force the needle and haystack to be converted to a string and try again to compare.
There is a reported bug that describes this situation: link

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question