Reputation: 45941
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.
Upvotes: 2
Views: 654
Reputation: 312
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!
Upvotes: 1
Reputation: 110725
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"
Upvotes: 2
Reputation: 29419
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.
Upvotes: 3
Reputation: 78523
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
The meat of it is in the NumberToRoundedConverter
class.
Upvotes: 0