Rails: math does not calculate correctly. It is off .00000000000001

My rails app does math incorrectly. I think this has something to do with variable types (int vs float), but not sure what is wrong.

The root problem is the method in my Stat model:

def lean_mass
 self.weight * 0.01 * (100 - self.body_fat)
end

Where

Stat.weight = 140
Stat.body_fat = 15

it returns 119.00000000000001instead 119.

However where

Stat.weight = 210
Stat.body_fat = 15

it returns the 178.5correct number.

Does anyone know why he throws this small decimal digit?

The data type for weight is an integer, and body_fat is decimal if that helps.

+4
source share
2 answers

. , . .

, :

0.1 + 0.2
#=> 0.30000000000000004

: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

, BigDecimal floats:

require 'bigdecimal'
BigDecimal.new('0.01') * 140 * (100 - 15)
#=> 119.0
+14

ruby ​​BigDecimal

, :

sum = 0
10_000.times do
  sum = sum + 0.0001
end
print sum #=> 0.9999999999999062

:

require 'bigdecimal'

sum = BigDecimal.new("0")
10_000.times do
  sum = sum + BigDecimal.new("0.0001")
end
print sum #=> 0.1E1
+3

All Articles