简体   繁体   中英

Array with hashes - How to round(2) the values

I have been trying for ages. I am trying to round an array with hashes.

[
  {
    :email => "user_01@yorlook.com",
    :amount => 129.22500000000002
  },
  {
    :email => "user_02@yorlook.com",
    :amount => 112.67500000000001
  }
]

I need a method to make it look like this:

[
  {
    :email => "user_01@yorlook.com",
    :amount => 129.23
  },
  {
    :email => "user_02@yorlook.com",
    :amount => 112.68
  }
]

Thanks for your help in advance!

Assuming arr always contains Hash with key amount which is a Float (as in example).

arr.each { |hash|
 hash[:amount] = hash[:amount].round(2)
}
#=> [{:email=>"user_01@yorlook.com", :amount=>129.23}, {:email=>"user_02@yorlook.com", :amount=>112.68}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM