8

i want to round off a number upto two decimal place in ruby such that

(0.02 * 270187).round(2) is 5403.74 which is correct

but

(0.02 * 278290).round(2) is 5565.8 which is not consistent with previous one

i want to make it look like 5565.80

Please tell me how can i do it in ruby

user4965201
  • 973
  • 1
  • 11
  • 25
  • 6
    [The answer to your question is found here, thanks.](http://stackoverflow.com/questions/15900537/to-d-to-always-return-2-decimals-places-in-ruby) – x6iae Nov 19 '15 at 11:07

2 Answers2

12

This will do the trick:

> sprintf("%.2f",(0.02 * 270187))
#=> "5403.74" 
> sprintf("%.2f",(0.02 * 278290))
#=> "5565.80"
> sprintf("%.2f",(0.02 * 270187)).to_f > 100  # If you plan to Compare something with result
#=> true 

OR

> '%.2f' % (0.02 * 270187)
#=> "5403.74"
> '%.2f' % (0.02 * 278290)
#=> "5565.80" 

Demo

Note: The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf can format any number almost any way you like. If you are planning to compare anything with this result then convert this string to float by adding .to_f at the end. Like this

Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
11

You could do something like

include ActionView::Helpers::NumberHelper

number_with_precision(value, :precision => 2) # value.to_f if you have string

or like this

'%.2f' % your_value

Hope it helps! Further you can read from here

Community
  • 1
  • 1
Dusht
  • 4,712
  • 3
  • 18
  • 24
  • i am getting ArgumentError (comparison of String with 0 failed) ... i am using this method in rails – user4965201 Nov 19 '15 at 11:16
  • You can convert your string to float like `value.to_f` – Dusht Nov 19 '15 at 11:18
  • i am getting some value as 0, think thats why i am getting the error – user4965201 Nov 19 '15 at 11:22
  • Can you please provide your code, where you are actually using it. – Dusht Nov 19 '15 at 11:23
  • cost = number_with_precision((to_mb(monthly_usage) * cost_per_mb).to_f, :precision => 2) – user4965201 Nov 19 '15 at 11:25
  • getting this error ArgumentError (comparison of ActiveSupport::SafeBuffer with 0 failed): – user4965201 Nov 19 '15 at 11:25
  • I am assuming, you are getting correct values from `to_mb(monthly_usage)` and `cost_per_mb`. Also have you included `include ActionView::Helpers::NumberHelper` ? Can you please also try with `'%.2f' % (to_mb(monthly_usage) * cost_per_mb)` – Dusht Nov 19 '15 at 11:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/95552/discussion-between-user4965201-and-dusht). – user4965201 Nov 19 '15 at 11:32
  • @user4965201 You can do `cost = ('%.2f' % (to_mb(monthly_usage) * cost_per_mb)).to_f` – Dusht Nov 19 '15 at 11:52