How to round value to 2 digits after coma or till first digit greater than 0 in Rails 3

StackOverflow https://stackoverflow.com/questions/18745673

  •  28-06-2022
  •  | 
  •  

I'd like round

  • if number is really small round till first digit greater than 0 and then round by 2 digits. Like this:

    value = 0.00000012344 => rounded_value = 0.00000012

    0.0035 to 0.0035

  • 2 digits after coma if it's just random floating number, like this:

    76.543554 to 76.5

  • else if it's integer, don't do anything

    100 stays 100

    44 stays 44

    etc

I'm using ruby 1.9.3 and I've tried value.round(2) which gives me only 0.00 and this doesn't satisfy me.

有帮助吗?

解决方案

i think number_with_precision is the perfect answer to your question

to have the result you're looking for, you should set the options :precision => 2 and :significant => true

for your given examples, you would use

number_with_precision(0.00000012344, :precision => 2, :significant => true)

number_with_precision(0.0035, :precision => 2, :significant => true)

number_with_precision(76.543554, :precision => 2, :significant => true)

for further precisions see the rails doc http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top