views:

262

answers:

2

I need to write the code that would format the value according to the specified options.

Right now there is several formatting options that can be chosen: rounding/truncating the number with the specified precision, added prefix (e.g $) or postfix (e.g. %), grouping thousands (applying commas), adding numeric abbreviations (KMB).

So e.g. number 1857 could be displayed as $2K or $1.86K or $ 1,867

At first I thought about using Decorator pattern for this but I am not sure because the formatters should be applied in a specific order,e.g. at first I need to apply KMB conversion: 1857 -> 1.857 K, then round it 1.86 K.

Do you have any suggestions?

Thanks, matali

+12  A: 

No, use the java.text.NumberFormat options that are already available to you. They're fully internationalized already.

duffymo
+1 Don't reinvent the wheel
Sometimes you have implement these things, banking business can be very picky
t3mujin
A: 

Assuming there's no existing implementation that suits your needs there are different options other than Decorator:

If you can decompose the formatting in rules (decimal separator, thousand separator, currency) then a Chain of Responsibility (http://www.dofactory.com/Patterns/PatternChain.aspx) where each block handles is rule can be an option, and you can run it on a specific order.

t3mujin