Calculating a simple decimal in rails console using postgresql

979 views Asked by At

Ok...I think I'm missing something very obvious here but haven't been able to google myself through this solution. I have two simple rails methods that calculate the number of up votes and down votes. They will always return a fraction because i'm trying to show a percentage (up_vote_count / votal_vote_count). I open the rails console and run the following:

y = @somespecificrecord

then...

y.up_vote_count

This returns 1 as is expected

y.down_vote_count

This returns 1 as is expected

y.total_vote_count

This returns 2 as is expected.

However, when I run in the console...

y.up_vote_count / y.total_vote_count

This returns 0 when it should return .50. I've been reading about floats/integers/decimals, etc and I do see this in the schema on the model i'm working from:

t.float "value", default: 0.0

Is this my problem?...and if so what do I have to do to allow myself to do a simple formula like the one above in rails console that will return the correct decimal rounded to 2 digits (i.e, .50 in this case above). I don't know if I want to run any migrations to change data types because this is a gem (& as a beginner I tend to stay away from customizing code from any gems I'm using). Is there another way? something small i'm missing hopefully?

UPDATE: I'm learning decimals are slower than floats also, so is there any way to accomplish this with continuing to use t.float "value", default: 0.0

thanks for any help.

2

There are 2 answers

0
Eyeslandic On BEST ANSWER
1 / 2 = 0.5 

With integers this will round down to 0

You can get around this by casting the divisor to a float, forcing it to do division with floating point accuracy.

y.up_vote_count / y.total_vote_count.to_f
0
MZaragoza On

Float

Float objects represent inexact real numbers using the native architecture's double-precision floating point representation.

Floating point has a different arithmetic and is an inexact number.

its important to know if you divide 2 hole numbers you are going to get a hole number. if you are looking a decimal you should first convert your numbers to a decimal or a "float" like this

up_votes   = y.up_vote_count.to_f 
total_vote = y.down_vote_count.to_f

(up_votes / total_vote) * 100.0

I hope that this helps