前言:
最近在做财务系统的开发功能,要求在导出的word文档里面的数字,要以千分位的格式处理显示,于是写了一下下面的方法,希望可以帮助到需要的小伙伴
/**
* 格式化数字为千分位显示;
* @param
* @return
*/
public static String fmtMicrometer(String text)
{
DecimalFormat df = null;
if(text.indexOf(".") > 0)
{
if(text.length() - text.indexOf(".")-1 == 0)
{
df = new DecimalFormat("###,##0.");
}else if(text.length() - text.indexOf(".")-1 == 1)
{
df = new DecimalFormat("###,##0.0");
}else if(text.length() - text.indexOf(".")-1 == 2)
{
df = new DecimalFormat("###,##0.00");
}else if(text.length() - text.indexOf(".")-1 == 3)
{
df = new DecimalFormat("###,##0.000");
}else if(text.length() - text.indexOf(".")-1 == 4)
{
df = new DecimalFormat("###,##0.0000");
}else if(text.length() - text.indexOf(".")-1 == 5)
{
df = new DecimalFormat("###,##0.00000");
}
}else
{
df = new DecimalFormat("###,##0");
}
double number = 0.0;
try {
number = Double.parseDouble(text);
} catch (Exception e) {
number = 0.0;
}
return df.format(number);
}
上面的代码主要进行判断小数点的位置,以及小数点前的位置进行格式化的处理,具体的方法:DecimalFormat
/**
* Creates a DecimalFormat using the given pattern and the symbols
* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
* This is a convenient way to obtain a
* DecimalFormat when internationalization is not the main concern.
* <p>
* To obtain standard formats for a given locale, use the factory methods
* on NumberFormat such as getNumberInstance. These factories will
* return the most appropriate sub-class of NumberFormat for a given
* locale.
*
* @param pattern a non-localized pattern string.
* @exception NullPointerException if <code>pattern</code> is null
* @exception IllegalArgumentException if the given pattern is invalid.
* @see java.text.NumberFormat#getInstance
* @see java.text.NumberFormat#getNumberInstance
* @see java.text.NumberFormat#getCurrencyInstance
* @see java.text.NumberFormat#getPercentInstance
*/
public DecimalFormat(String pattern) {
// Always applyPattern after the symbols are set
this.symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT));
applyPattern(pattern, false);
}
占位符的处理;