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?
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)
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.