|
Rails Arithmetic: Add, Subtract, Multiply, and Divide
By: Bruce Bahlmann - Contributing Author (your
feedback
is important to us!)
In rails development, you will often want to use basic arithmetic. While all
these work as you would expect, rails doesn't handle results well -
particularly those results which do not come in the form of a whole number.
So, this post is all about handling rails results that come of the form of a
fraction or what rails call them (floats).
Below, we break down various mathematical operations (beginning with
division) and how to achieve the kind of results you want without having to
hunt-n-peck your way through various incomplete rails posts to find what you
are looking for:
[Division]
4/2
=> 2
1/2
=> 0
7/3
=> 2
Float(1)/2
=> 0.5
Float(7)/3
=> 2.33333333333333
(Float(7)/3).round(2)
=> 2.33
3.6/1.2
=> 3
3.8/0.7
=> 5.42857142857143
(3.8/0.7).round(4)
=> 5.4286
RECOMMENDED METHOD:
(Float x/y)
=> result that always observes fraction
Notice above, that when using a whole number as the dividend (top
number) and the divisor (bottom number) the results will be truncated as if
rails thought it were only working with integers (whole numbers). To resolve
this, you need to declare the dividend as a float (see above) - but only if
dividend and divisor are whole numbers. Note that if either the dividend or
the divisor is a real number (float), rails properly states the results as a
fraction (if any). To be safe, it is probably best to declare the
dividend as a float to ensure rails properly produces a fraction when it is
supposed to.
Multiplication:
[multiplication]
Common errors when working with numbers:
[can't convert Fixnum into String]
@survey["delta"] = (@survey.inviteListing.size - @survey.completedListing.size) +" is the difference"
=> "can't convert Fixnum into String"
USE Instead:
@survey["delta"] = "#{(@survey.inviteListing.size - @survey.completedListing.size)}" +" is the difference"
This is a work in progress.
This is a work in progress...
.
Can Birds-Eye.Net help you or your Company?
Receive your Birds-Eye.Net articles and white
papers hot off
the presses by adding our RSS feed to your reader.
|
|
|
(C) Copyright Birds-Eye.Net, All rights reserved.
It is against the law to reproduce this content or any portion of it in any form without the explicit written permission of Birds-Eye Network Services, LLC. Federal copyright law (17 USC 504) makes it illegal, punishable with fines up to $100,000 per violation plus attorney's fees.
|