如何检查数字是否有小数?

时间:2022-06-20 17:06:22

I want to specifically check if a given number contains ".5"

我想具体检查给定的数字是否包含“.5”

I'm only dealing with whole numbers and halves (0.5, 1, 1.5, etc).

我只处理整数和一半(0.5,1,1.5等)。

5 个解决方案

#1


22  

% should work

% 应该管用

variable % 1 != 0

变量%1!= 0

Check this fiddle

检查这个小提琴

Edit: Here is a rubyfiddle

编辑:这是一个红宝石

#2


8  

Always use BigDecimal to check the fractional part of a number to avoid floating point errors:

始终使用BigDecimal检查数字的小数部分以避免浮点错误:

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

#3


7  

myValue == myValue.floor

myValue == myValue.floor

or if you really want to check specifically for 0.5, 1.5 etc

或者如果你真的想特别检查0.5,1.5等

myValue - myValue.floor == 0.5

myValue - myValue.floor == 0.5

#4


2  

(2.50).to_s.include?('.5') #=> true
(2).to_s.include?('.5') #=> false

#5


-1  

Try

n = 1.5
# => 1.5

n - Integer(n) == 0.5
# => true

#1


22  

% should work

% 应该管用

variable % 1 != 0

变量%1!= 0

Check this fiddle

检查这个小提琴

Edit: Here is a rubyfiddle

编辑:这是一个红宝石

#2


8  

Always use BigDecimal to check the fractional part of a number to avoid floating point errors:

始终使用BigDecimal检查数字的小数部分以避免浮点错误:

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

#3


7  

myValue == myValue.floor

myValue == myValue.floor

or if you really want to check specifically for 0.5, 1.5 etc

或者如果你真的想特别检查0.5,1.5等

myValue - myValue.floor == 0.5

myValue - myValue.floor == 0.5

#4


2  

(2.50).to_s.include?('.5') #=> true
(2).to_s.include?('.5') #=> false

#5


-1  

Try

n = 1.5
# => 1.5

n - Integer(n) == 0.5
# => true