java编程如何保留两位小数

如题所述

方式一:

四舍五入
double f = 111231.5585;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
保留两位小数
---------------------------------------------------------------

方式二:

java.text.DecimalFormat df =new java.text.DecimalFormat("#.00");
df.format(你要格式化的数字);

例:new java.text.DecimalFormat("#.00").format(3.1415926)

#.00 表示两位小数 #.0000四位小数 以此类推...

方式三:

double d = 3.1415926;

String result = String .format("%.2f");

%.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型

方式四:

NumberFormat ddf1=NumberFormat.getNumberInstance() ;

void setMaximumFractionDigits(int digits)
digits 显示的数字位数
为格式化对象设定小数点后的显示的最多位,显示的最后位是舍入的
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-02

可以使用java.math.BigDecimal类去进行数学方面的运算,里面有方法取精度。


比如除法:

public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode)


第二个参数就是精度

可以自己查看详细的API文档学习


像你说的需要保留两位小数,举个例子:

BigDecimal bd = new BigDecimal("12.345678");
System.out.println(bd.setScale(2, RoundingMode.HALF_UP)); //12.35

本回答被提问者和网友采纳
第2个回答  2013-11-26
自己定义格式,使用String.fromat.例如
private final string OutputPathFormat = "{0}\\{1:yyyyMMdd}";
outPath = string.Format(OutputPathFormat, outPath.TrimEnd('\\'), now)其中0表示第一个参数,1表示第二个参数
第3个回答  2013-11-26
double f = 111231.5585;

System.out.println(String.format("%.2f", f));
第4个回答  2015-09-11
float scale = (float) 22.224465;
DecimalFormat fnum = new DecimalFormat("##0.00");
String dd=fnum.format(scale);
System.out.println(dd);
相似回答