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

On 10ÔÂ4ÈÕ, ÉÏÎç10ʱ03·Ö, “[email protected]

Think theres a bit missing off the end?

Can I use printf inside a rhtml?

Charles

On Oct 4, 6:52 am, Rob B. [email protected] wrote:

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.

On Oct 4, 2007, at 2:22 PM, Stan K. wrote:

    "%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 :wink:

$ 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 B. http://agileconsultingllc.com
[email protected]

On Oct 4, 2007, at 3:57 AM, [email protected] wrote:

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

Thanks,
Charles

Rob B. http://agileconsultingllc.com
[email protected]

Thanks guys, number_with_precision does the job for me.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs