您的位置:首页 > 其它

用DecimalFormat格式化十进制数字的实际应用

2017-02-10 14:52 435 查看
在项目中,有时候我们需要将数字转换成特定的格式便于操作和使用。最常用的就是在操作价格数字的时候,需要将数字转换成小数点后保留两位小数,比如讲3.4转换成3.40

我们可以用DecimalFormat,它是NumberFormat的一个子类,它包含一个模式和一组符号:

0 一个数字

# 一个数字,不包括 0

. 小数的分隔符的占位符

, 分组分隔符的占位符

; 分隔格式。

- 缺省负数前缀。

% 乘以 100 和作为百分比显示

? 乘以 1000 和作为千进制货币符显示;用货币符号代替;如果双写,用国际货币符号代替。如果出现在一个模式中,用货币十进制分隔符代替十进制分隔符。

X 前缀或后缀中使用的任何其它字符,用来引用前缀或后缀中的特殊字符。

举例说明:写一个函数将float类型的数字转换成包含两位小数,返回String类型。

1     public static String getFormatString(Float price){
2         String parten = "#.##";
3         DecimalFormat decimal = new DecimalFormat(parten);
4         String price2= decimal.format(price);
5         try {
6             price2.charAt( price2.indexOf(".")+2);
7         }
8         catch (Exception e) {
9             price2 = price2 +"0";
10         }
11         return price2;
12     }


在这里有个问题需要读者思考,为什么需要加上try catch呢?

————————————————分隔符————————————————————————————————

//2017-3-24更新

今天又学到保留两位小数的其他办法:

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class format {
double f = 111231.5585;
public void m1() {
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
}
/**
* DecimalFormat转换最简便
*/
public void m2() {
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));
}
/**
* String.format打印最简便
*/
public void m3() {
System.out.println(String.format("%.2f", f));
}
public void m4() {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(f));
}
public static void main(String[] args) {
format f = new format();
f.m1();
f.m2();
f.m3();
f.m4();
}
}


————————————————分隔符————————————————————————————————

//2017-3-24更新

之前代码中如果输入参数是123,返回的还是123,没有保留两位小数,现在调整代码如下可以解决问题:

public static String getFormatString(float price){
String parten = "#.##";
DecimalFormat decimal = new DecimalFormat(parten);
String price2= decimal.format(price);
int index = price2.indexOf(".");
System.out.println(index);
try {
if(index == -1){
price2 = price2 +".00";
}
price2.charAt( price2.indexOf(".")+2);
}
catch (Exception e) {
price2 = price2 +"0";
}
return price2;
}


2017-5-14:

除了自己写函数来处理外,String类提供的format方法功能十分强大,能处理整数,浮点,日期等等多种类型。
http://www.cnblogs.com/fsjohnhuang/p/4094777.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: