Java Float Double浮点保留两位小数的三种实现方法

1,利用Math.round函数

float YHAmount=Math.round(YHAmount * 100) / 100f;

2,使用 String.format() 

 String formattedRealAmount = String.format("%.2f", YHAmount);
 YHAmount = Float.parseFloat(formattedRealAmount);

3,利用DecimalFormat

float f = 0.5555f;

DecimalFormat df1 = new DecimalFormat("#.00");//保留两位小数,如果是零点几,则小数点前的0不显示,小数点后几个零就保留几位
DecimalFormat df2 = new DecimalFormat("0.00");//首位0显示出来,即0.1显示为 0.1

df1.format(f);
df2.format(f);

综上,优先使用Math,简单方便,使用DecimalFormat需要引用单独的包

猜你喜欢

转载自blog.csdn.net/wh445306/article/details/130162526