简体   繁体   English

格式化数字的最佳设计模式是什么?

[英]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). 现在可以选择几种格式化选项:使用指定的精度舍入/截断数字,添加前缀(例如$)或后缀(例如%),分组数千(应用逗号),添加数字缩写(KMB)。

So eg number 1857 could be displayed as $2K or $1.86K or $ 1,867 因此,例如,数字1857可以显示为$ 2K或$ 1.86K或$ 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. 起初我考虑过使用Decorator模式,但我不确定,因为格式化程序应该按特定顺序应用,例如,首先我需要应用KMB转换:1857 - > 1.857 K,然后将其舍入1.86 K.

Do you have any suggestions? 你有什么建议吗?

Thanks, matali 谢谢,matali

No, use the java.text.NumberFormat options that are already available to you. 不,使用已经可用的java.text.NumberFormat选项。 They're fully internationalized already. 他们已经完全国际化了。

Assuming there's no existing implementation that suits your needs there are different options other than Decorator: 假设没有适合您需求的现有实现,除了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. 如果你可以分解规则中的格式(小数点分隔符,千位分隔符,货币),那么每个块处理规则的责任链( http://www.dofactory.com/Patterns/PatternChain.aspx )可以是一个选项,并且您可以按特定订单运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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