Set the Display Precision of a Float in Ruby

How to display output with two digits of precision

You can use this:

puts "Your balance is #{'%.02f' % a.rem}"

But remember that this code will round your result if you have more than 2 decimal places. Ex.: 199.789 will become 199.79.

Convert string to float with precision

That string represents the value 1909 so merely to_fing it won't work. You need to divide by 100.0 to move the decimal point over two "houses" as you so eloquently put it:

"000001909".to_f / 100.0 # => 19.09

Having a string with a dot in it will output the expected result as well:

"0000019.09".to_f # => 19.09

Only show decimal point if floating point component is not .00 sprintf/printf

You want to use %g instead of %f:

"%gx" % (factor / 100.00)

How do you round a float to 2 decimal places in JRuby?

Float#round can take a parameter in Ruby 1.9, not in Ruby 1.8. JRuby defaults to 1.8, but it is capable of running in 1.9 mode.

Ruby: Rounding float in Ruby

When displaying, you can use (for example)

>> '%.2f' % 2.3465
=> "2.35"

If you want to store it rounded, you can use

>> (2.3465*100).round / 100.0
=> 2.35

Rails 3. How to display two decimal places in edit form?

You should use number_with_precision helper. See doc.

Example:

number_with_precision(1.5, :precision => 2)
=> 1.50

Within you form helper:

<%= f.text_field :cost, :class => 'cost', :value => (number_with_precision(f.object.cost, :precision => 2) || 0) %>

BTW, if you really want to display some price, use number_to_currency, same page for doc (In a form context, I'd keep number_with_precision, you don't want to mess up with money symbols)




Related Topics



Leave a reply



Submit