ava 取小数点前两位的4种办法
//取小数点的几种办法
class TestDot2
{
//方法1
public void test1(double c)
{
java.text.
DecimalFormat df = new java.text.DecimalFormat("#.##");
System.out.println(df.format(c));
}
//方法2
public void test2(double c)
{
java.math.BigDecimal bd = new java.math.BigDecimal(String.valueOf(c));
bd = bd.setScale(2,java.math.BigDecimal.ROUND_HALF_UP);
System.out.println(bd);
}
//方法3
public void test3(double c)
{
long l1 = Math.round(c*100); //四舍五入
double ret = l1/100.0; //注意:使用 100.0 而不是 100
System.out.println(ret);
}
//方法4
public void test4(double c)
{
c=((int)(c*100))/100.0;
System.out.println(c);
}
public static void main(String[] args)
{
double c = 3.056;
TestDot2 td2 = new TestDot2();
//td2.test1(c);
//td2.test2(c);
//td2.test3(c);
td2.test4(c);
}
}