I want to put in a space at every third character when formatting a number. According to this spec:
it "should format an amount" do
spaces_on( 1202003 ).should == "1 202 003"
end
and I came up with this piece of code that does the job
def spaces_on amount
thousands = amount / 1000
remainder = amount % 1000
if thousands == 0
"#{remainder}"
else
zero_padded_remainder = '%03.f' % remainder
"#{spaces_on thousands} #{zero_padded_remainder}"
end
end
So my question is if this was the best way to do it. I suspect that there may be a regex way around it but I am not sure I will like the readability of that. (On the other hand - the %03.f magic is not very readable either....)