I want to specifically check if a given number contains ".5"
I'm only dealing with whole numbers and halves (0.5, 1, 1.5, etc).
%
should workvariable % 1 != 0
Check this RubyFiddle.
Here is a JavaScript fiddle, too.
Always use BigDecimal
to check the fractional part of a number to avoid floating point errors:
require 'bigdecimal'
BigDecimal.new(number).frac == BigDecimal("0.5")
For example:
BigDecimal.new("0.5").frac == BigDecimal("0.5")
# => true
BigDecimal.new("1.0").frac == BigDecimal("0.5")
# => false
And a more general solution to see if a number is whole:
BigDecimal.new("1.000000000000000000000000000000000000000001").frac.zero?
# => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With