Jon Schneider
Jon Schneider

Reputation: 26973

Make Rails' number_to_percentage output a dynamic count of decimals, based on the input value?

I'd like to use Rails' number_to_percentage method to display a decimal number that I have in the range 0 to 100 as a percentage, including all of the number's decimal digits, and no unnecessary trailing zeroes.

Some example inputs and their corresponding desired outputs:

12        => "12%"
12.3      => "12.3%"
12.34     => "12.34%"
12.345    => "12.345%"
12.3456   => "12.3456%"

As the documentation states, number_to_percentage has a default precision of 3, so number_to_percentage(12.3456) yields "12.346%" instead of my desired value. Similarly, number_to_percentage(12) yields "12.000%" instead of just "12%".

I've experimented with combinations of different values for the precision, significant, and strip_insignificant_zeroes options to number_to_percentage, but without getting it to yield my desired results.

Is there a way a use number_to_percentage such that it yields my desired results? Or is this not the intended function of number_to_percentage, and I should take a different approach -- such as simply appending '%' to the end of my input using basic string manipulation?

Upvotes: 1

Views: 873

Answers (2)

Sara Fuerst
Sara Fuerst

Reputation: 6068

First you need to determine how many digits are after the decimal. You can do so using the following:

precision= n.to_s.partition('.').last.size

You can then set the precision value you want.

number_to_percentage(num, precision: precision)

Upvotes: 2

infused
infused

Reputation: 24337

Setting the precision to a number higher than you'll need and also setting strip_insignificant_zeros to true gives the desired results:

number_to_percentage 12, precision: 100, strip_insignificant_zeros: true
#=> "12%"

number_to_percentage 12.3, precision: 100, strip_insignificant_zeros: true
#=> "12.3%"

number_to_percentage 12.34, precision: 100, strip_insignificant_zeros: true
#=> "12.34%"

number_to_percentage 12.345, precision: 100, strip_insignificant_zeros: true
#=> "12.345%"

number_to_percentage 12.3456, precision: 100, strip_insignificant_zeros: true
#=> "12.3456%"

Upvotes: 4

Related Questions