我有一个哈希,其中键是几个月,我想将对象转换为正数和货币。
INPUT
hash = {
12 => -5888.969999999999,
4 => -6346.1,
3 => -6081.76,
2 => -5774.799999999999,
1 => -4454.38
}
输出
hash = {
12 => 5888.96,
4 => 6346.10,
3 => 6081.76,
2 => 5774.79,
1 => 4454.38
}
#Output should be a float
非常感谢任何帮助。
答案 0 :(得分:2)
尝试
hash.transform_values{|v| v.round(2).abs()}
或
hash.update(hash){|k,v| v.round(2).abs()}
答案 1 :(得分:0)
可以应用Numeric.abs()以确保数字为正数,Float.round(2)将浮点数舍入为2位小数。有关用法示例,请参阅ruby-doc.org/core-2.1.4/Numeric.html#method-i-abs和ruby-doc.org/core-2.2.2/Float.html#method-i-round。请注意,round()不会添加尾随零,因为这不会影响数值,但是可以通过格式化添加尾随零,例如:
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