Converting hash ruby objects to positive currency

384 views Asked by At

I have a hash where the keys are the months and I want to convert the objects to positive numbers AND currency.

INPUT

hash = {
  12 => -5888.969999999999,
  4 => -6346.1,
  3 => -6081.76,
  2 => -5774.799999999999,
  1 => -4454.38
}

OUTPUT

hash = {
    12 => 5888.96,
    4 => 6346.10,
    3 => 6081.76,
    2 => 5774.79,
    1 => 4454.38
}

#Output should be a float

Any help would be greatly appreciated.

2

There are 2 answers

1
AudioBubble On BEST ANSWER

Numeric.abs() can be applied to ensure a number is positive and Float.round(2) will round a float to 2 decimal places. See ruby-doc.org/core-2.1.4/Numeric.html#method-i-abs and ruby-doc.org/core-2.2.2/Float.html#method-i-round for usage examples. Note that round() will not add trailing zeros since that does not affect numerical value, however trailing zeros can be added by formatting, for example:

hash = {
  12 => -5888.969999999999,
  4 => -6346.1,
  3 => -6081.76,
  2 => -5774.799999999999,
  1 => -4454.38
}

# transform hash values
hash.each do |key, value|
  hash[key] = value.abs().round(2)
end

# print the modified hash without formatting the values
hash.each do |key, value|
  puts "#{key} => #{value}"
end

# prints 
# 12 => 5888.97
# 4 => 6346.1
# 3 => 6081.76
# 2 => 5774.80
# 1 => 4454.38

# print hash with values formatted with precision of 2 digits
hash.each do |key, value|
  puts "#{key} => #{'%.2f' % value}"
end

# prints
# 12 => 5888.97
# 4 => 6346.10
# 3 => 6081.76
# 2 => 5774.80
# 1 => 4454.38
2
Darpa On

Try

hash.transform_values{|v| v.round(2).abs()}

or

hash.update(hash){|k,v| v.round(2).abs()}