Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if number has a decimal?

Tags:

ruby

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).

like image 264
Shpigford Avatar asked Apr 18 '13 15:04

Shpigford


2 Answers

% should work

variable % 1 != 0

Check this RubyFiddle.

Here is a JavaScript fiddle, too.

like image 97
karthikr Avatar answered Oct 28 '22 17:10

karthikr


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
like image 20
Stefan Avatar answered Oct 28 '22 18:10

Stefan