# Problem with display of float types

Hello all,

I am taking some values from mysql columns of type float (16, 2) , performing a calculation such as multiply or divide, before displaying on screen, and then displaying on a screen.

Unfortunately, sometimes the value has many decimal places displayed! (Eg 136.5325325) Is there a way I can limit it to only display 2 decimal places?

Thanks, Charles

hi,     if you only wanna display it precisely as you wish, use "printf"

Br

Think theres a bit missing off the end?

Can I use printf inside a rhtml?

Charles

Think theres a bit missing off the end?

Can I use printf inside a rhtml?

Charles

Of course you can, it's just Ruby. If you want to stay with a Rails solution, try number_with_precision(136.5325325, 2) (and then look at the source for that method and you won't need the method anymore)

-Rob

number_with_precision doesn't round correctly, though. From the source:

# Formats a +number+ with the specified level of +precision+ (e.g., 112.32 has a precision of 2). The default       # level of precision is 3.

Of course you can, it's just Ruby. If you want to stay with a Rails solution, try number_with_precision(136.5325325, 2) (and then look at the source for that method and you won't need the method anymore)

number_with_precision doesn't round correctly, though. From the source:

# Formats a +number+ with the specified level of +precision+ (e.g., 112.32 has a precision of 2). The default       # level of precision is 3.       #       # ==== Examples       # number_with_precision(111.2345) # => 111.235       # number_with_precision(111.2345, 2) # => 111.24       # number_with_precision(13, 5) # => 13.00000       # number_with_precision(389.32314, 0) # => 389       def number_with_precision(number, precision=3)         "%01.#{precision}f" % number       rescue         number       end

111.2345 to two decimal places should be 111.23, not 111.24.

The doc is wrong -- probably written by a human

\$ script/console Loading development environment. >> helper.number_with_precision(111.2345, 2) => "111.23"

I suspect the aforementioned human applied the precision=2 to the result of the precision=3 shown just above it rather than the original 111.2345 argument.

-Rob

Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com

Thanks guys, number_with_precision does the job for me.