Skip to content

Commit

Permalink
[Fix #12146] Fix a false positive for Lint/FloatComparison
Browse files Browse the repository at this point in the history
  • Loading branch information
Earlopain committed Nov 29, 2023
1 parent 16e8a30 commit 7a66f24
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12146](https://github.com/rubocop/rubocop/issues/12146): Fix a false positive for `Lint/FloatComparison` when comparing against zero. ([@earlopain][])
10 changes: 10 additions & 0 deletions lib/rubocop/cop/lint/float_comparison.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ module Lint
# # good - using BigDecimal
# x.to_d == 0.1.to_d
#
# # good - comparing against zero
# x == 0.0
# x != 0.0
#
# # good
# (x - 0.1).abs < Float::EPSILON
#
Expand All @@ -39,6 +43,8 @@ class FloatComparison < Base

def on_send(node)
lhs, _method, rhs = *node
return if literal_zero?(lhs) || literal_zero?(rhs)

add_offense(node) if float?(lhs) || float?(rhs)
end

Expand All @@ -59,6 +65,10 @@ def float?(node)
end
end

def literal_zero?(node)
node&.numeric_type? && node.value.zero?
end

# rubocop:disable Metrics/PerceivedComplexity
def check_send(node)
if node.arithmetic_operation?
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/lint/float_comparison_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,16 @@
(x - 0.1) < epsilon
RUBY
end

it 'does not register an offense when comparing against zero' do
expect_no_offenses(<<~RUBY)
x == 0.0
x.to_f == 0
x.to_f.abs == 0.0
x != 0.0
x.to_f != 0
x.to_f.zero?
x.to_f.nonzero?
RUBY
end
end

0 comments on commit 7a66f24

Please sign in to comment.