2

Is it possible to use Ruby number formatting (such as sprinf or other?) to format floats with spaces after every 3 decimal places?

1.5         => 1.5
1.501       => 1.501
1.501001    => 1.501 001
1.501001001 => 1.501 001 001

Is there another easy way to do it?

Working in Ruby, not Rails.

B Seven
  • 44,484
  • 66
  • 240
  • 385

4 Answers4

3

I don't believe there is any built-in support for this, but you can change the behavior of Float#inspect and Float#to_s as follows:

class Float
  alias :old_inspect :inspect
  def inspect
     pieces = old_inspect.split('.')
     if pieces.length == 1
       pieces[0]
     else
       pieces[1].gsub!(/(...)(?!$)/,'\1 ')
       pieces.join('.')
     end
  end
  alias :to_s :inspect
end

Note: I only minimally tested this and there are certainly more elegant ways to code it in terms of the Ruby string operations. There is also significant risk this will screw up code that depends on the traditional float formatting.

Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106
2

Using String methods:

def add_sep(s, n=3, sep=' ')
  s.split('').each_slice(n).map(&:join).join(sep)
end

def add_spaces(fl)
  f, l = fl.to_s.split('.')
  f + '.' + add_sep(l)
end  

add_spaces(1.5)         # => "1.5"
add_spaces(1.501)       # => "1.501"
add_spaces(1.50101)     # => "1.501 01"
add_spaces(1.501011)    # => "1.501 011"
add_spaces(1.501001001) # => "1.501 001 001"

def add_spaces_both_sides(fl)
  f, l = fl.to_s.split('.')
  add_sep(f.reverse).reverse + '.' + add_sep(l)
end  

add_spaces_both_sides(1234567.12345) # => "1 234 567.123 45" 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
1

You can accomplish this by opening the Float class and adding the following method:

class Float
  def format_spaced
    parts = self.to_s.split(".")
    parts[0] + "." + parts[1].scan(/\d{1,3}/).join(" ")
  end
end

f = 1.23456789
f.format_spaced  # => "1.234 567 89"

Fairly straightforward I hope!

Jeff Klein
  • 312
  • 3
  • 8
0

It's technically part of rails, but you could grab some code from the number helpers. Namely number_with_delimiter:

number_with_delimiter(98765432.98, delimiter: " ", separator: ",")
# => 98 765 432,98

http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_delimiter

The meat of it is in the NumberToRoundedConverter class.

Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154