简体   繁体   中英

What's the best design pattern for formatting numbers?

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 (eg $) or postfix (eg %), grouping thousands (applying commas), adding numeric abbreviations (KMB).

So eg 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,eg 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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM