1.方法一:
float a = 43.8776f;
a= (float)(Math.round((double)a*100)/100.00);
2.方法二
float ft = 134.3435f;
int scale = 2;//设置位数
int roundingMode = 4;//表示四舍五入,可以选择其他舍值方式,例如去尾,等等.
BigDecimal bd = new BigDecimal((double)ft);
bd = bd.setScale(scale,roundingMode);
ft = bd.floatValue();
3.方法三:
有个更简单的方法:
import java.text.DecimalFormat;
String a = new DecimalFormat("###,###,###.##").format(100.12345 );
a='100.12'
4.方法四:
float a = 123.2334f;
float b = (float)(Math.round(a*100))/100;
System.out.println("b="+b);
float a = 43.8776f;
a= (float)(Math.round((double)a*100)/100.00);
2.方法二
float ft = 134.3435f;
int scale = 2;//设置位数
int roundingMode = 4;//表示四舍五入,可以选择其他舍值方式,例如去尾,等等.
BigDecimal bd = new BigDecimal((double)ft);
bd = bd.setScale(scale,roundingMode);
ft = bd.floatValue();
3.方法三:
有个更简单的方法:
import java.text.DecimalFormat;
String a = new DecimalFormat("###,###,###.##").format(100.12345 );
a='100.12'
4.方法四:
float a = 123.2334f;
float b = (float)(Math.round(a*100))/100;
System.out.println("b="+b);
本文介绍了四种在Java中将浮点数保留为两位小数的方法,包括使用Math类进行四舍五入、BigDecimal类的setScale方法、DecimalFormat类格式化字符串以及直接通过Math类和类型转换实现。
5644

被折叠的 条评论
为什么被折叠?



