[英]Converting hash ruby objects to positive currency
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. 任何帮助将不胜感激。
Try 尝试
hash.transform_values{|v| v.round(2).abs()}
or 要么
hash.update(hash){|k,v| v.round(2).abs()}
Numeric.abs() can be applied to ensure a number is positive and Float.round(2) will round a float to 2 decimal places. 可以使用Numeric.abs()来确保数字为正,并且Float.round(2)会将float舍入到小数点后两位。 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.
有关使用示例,请参见ruby-doc.org/core-2.1.4/Numeric.html#method-i-abs和ruby-doc.org/core-2.2.2/Float.html#method-i-round。 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:
请注意,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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.