Topic: setting the number of decimal points in a float

Does anyone have any idea of how to set this? I have tried adding them after the fact with regular expressions, but I would have thought there is an easier way.

Re: setting the number of decimal points in a float

Perhaps what you want is a "Decimal" type? This is added to Rails in 1.2 and edge so you can specify a "decimal" type column in the database. This allows you to specify how many decimal places you want. See this post for details.

Railscasts - Free Ruby on Rails Screencasts

Re: setting the number of decimal points in a float

maybe a printf?

printf("Float: %5.2f", "#{@float_number}")

5 numbers, 2 after the decimal. (5.2)

If not that, force the decimal point?

number / 60.0

http://danielfischer.com - Personal Web-Technology-Blog, Los Angeles.

Re: setting the number of decimal points in a float

thanks for the help guys

Re: setting the number of decimal points in a float

dahuk wrote:

thanks for the help guys

Did you find the proper solution?

And np smile

Last edited by DFischer (2007-01-16 18:54:41)

http://danielfischer.com - Personal Web-Technology-Blog, Los Angeles.

Re: setting the number of decimal points in a float

The code is in my application helper and so I could not use the printf, and I am not on rails 1.2 quite yet, so I came up with an intermediate solution and learned a bit more about regular expressions in the process.

What I had was a column in a table where the values were:
0.0
-0.25
-0.5
-0.75
-1.0
-1.25
..
..
-6.0

As you can see they don't line up nicely so I used a regular expression to find everything that had a '.0' or '.5' in it, and then append 0 to that. This application will never have values ending in anything other than .0, .25, .5, or .75, so I won't have to worry about it getting messy in the future.

My code was:

#old
table_str << "<td class = \"headercol\">" + lens.sphere.to_s + "</td>"

#and the new is
table_str << "<td class = \"headercol\">" + (lens.sphere.to_s =~ /\.(0|5)/ ? "#{$`}#{$&}#{$'}0" : lens.sphere.to_s ) + "</td>"


lens.sphere.to_s =~ /\.(0|5)/ checks if the sphere has a '.' followed by either a '0' or a '5'
If so it appends a '0' to the string, and if not it just passed the original.

Re: setting the number of decimal points in a float

dahuk wrote:

The code is in my application helper and so I could not use the printf, and I am not on rails 1.2 quite yet, so I came up with an intermediate solution and learned a bit more about regular expressions in the process.

Use sprintf (notice I didn't say printf) instead of regular expressions.

http://www.rubycentral.com/ref/ref_m_ke … ml#sprintf

vinnie - rails forum admin

Re: setting the number of decimal points in a float

Thanks, that does quite a bit for readability. I've changed that segment of code to:

sprintf("%+#1.2f", lens.sphere)