Search code examples
rubyarraysfloating-point-precisionzerofloating-point-conversion

Sorting arrays containing numbers with 3 decimals and keeping trailing zeroes (Ruby)


I have an array with the following numbers

numbers = [70.920, -38.797, 14.354, 99.323, 90.374, 7.581]

I would like to sort them numerically, but the problem is ruby automatically rounds numbers with trailing zeroes. I would like to keep the format to three decimal places and for the trailing zeroes to be ignored.

When I declare the numbers array, I get this output.

=> [70.92, -38.797, 14.353, 99.323, 90.374, 7.581]

I tried to map the array to include 3 decimal places and then convert them back to floats.

number.map { |n| "%.3f" % n }.map(&:to_f).sort

Once again, Ruby trims the trailing zeroes.

[-38.797, 7.581, 14.354, 70.92, 90.374, 99.323]

I was expecting the input to look like this

[-38.797, 7.581, 14.354, 70.920, 90.374, 99.323]

I've used the Float Documentation as a reference, but can't figure out how to implement this

http://ruby-doc.org/core-2.2.0/Float.html

Is this possible in Ruby? Thanks in advance.


Solution

  • Are you using the input representation with trailing zeros only for visualization purposes? You can use the array as ruby use it, removing trailing zeroes. And when you need to present the input, use something like:

    numbers.sort.map{|n|sprintf "%.3f", n}