Luigi
Luigi

Reputation: 5603

Convert hash values from decimal to percentage in Ruby

I am creating a table within a PDF using the following hash:

percentages = {
"group one" => 0.2,
"group two" => 0.6666666666666666,
"group three" => 0.2,
"group four" => 0.03333333333333333,
"group five" => 0.03333333333333333,
"group six" => 0.06666666666666667
}

I am calling .transpose on the hash keys and values:

[percentages.keys, percentages.values].transpose

This works as expected, but I now need to convert the decimals to percentages. Instead of .2, I need to show 20%. Instead of 0.06666666666666667, I need to show 7%.

Is there a clean way to do this without altering the original hash/creating a new one?

Upvotes: 2

Views: 1938

Answers (4)

the Tin Man
the Tin Man

Reputation: 160551

A convenient way to convert and round uses String.% which is akin to format, printf or sprintf in the Kernel:

[
  0.2,
  0.6666666666666666,
  0.2,
  0.03333333333333333,
  0.06666666666666667
].each do |f|
  puts "%.0f%%" % (f * 100)
end
# >> 20%
# >> 67%
# >> 20%
# >> 3%
# >> 7%

From that point it's easy to build the rest of what you're looking for.

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110675

Another way, using zip rather than transpose:

percentages.keys.zip percentages.values.map {|v| "#{(100*v).round.to_s}%"}
  #  => [["group one", "20%"], ["group two", "67%"], ["group three", "20%"],
  #      ["group four", "3%"], ["group five", "3%"], ["group six", "7%"]] 

Upvotes: 2

sawa
sawa

Reputation: 168091

percentages.map{|k, v| [k, "#{(v * 100).round}%"]}

Upvotes: 3

tckmn
tckmn

Reputation: 59273

You could try

[percentages.keys, percentages.values.map {|x| (x * 100).round.to_s + '%'}].transpose

It simply takes each value and multiplies by 100 (converts to percentage), calls round (to remove the decimal, i.e. 6.666667 -> 7), and then calls to_s to convert it to a string and concatenate to '%'.

Upvotes: 4

Related Questions