1.第一个
package ext;
import java.math.BigDecimal;
public class Text4 {//四舍五入
public static void main(String[]args){
double f =123456.78910;
BigDecimal b = new BigDecimal(f);
double f1 =b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
}
}
//111231.56
2.第二个
package ext;
import java.text.DecimalFormat;
public class Text4 {//四舍五入
public static void main(String[]args){
double d=1234.45678;
DecimalFormat dFormat=new DecimalFormat("#.00");
System.out.println(dFormat.format(d));
}
}
//1234.46
3.第三个
NumberFormat ddf1=NumberFormat.getNumberInstance() ;
void setMaximumFractionDigits(int digits)
digits 显示的数字位数 为格式化对象设定小数点后的显示的最多位,显示的最后位是舍入的
package ext;
import java.text.NumberFormat;
public class Text4 {//四舍五入
public static void main(String[]args){
double x=23.5455;
NumberFormat ddf1=NumberFormat.getNumberInstance() ;
ddf1.setMaximumFractionDigits(2);
String s= ddf1.format(x) ;
System.out.print(s);
}
}
//23.55
4.第四个
/*
Java中也没有提供保留指定位数的四舍五入方法,只提供了一个Math.round(double d)和Math.round(float f)的方法。 分别返回长整型和整型值。round方法不能设置保留几位小数,我们只能象这样(保留两位): public double round(double value){ return Math.round( value * 100 ) / 100.0; } 但给这个方法传入4.015它将返回4.01而不是4.02,如我们在上面看到的 4.015 * 100 = 401.49999999999994 因此如果我们要做到精确的四舍五入,这种方法不能满足我们的要求。 还有一种方式是使用java.text.DecimalFormat,但也存在问题,format采用的舍入模式是ROUND_HALF_DOWN(舍入模式在下面有介绍), 比如说4.025保留两位小数会是4.02,因为.025距离” nearest neighbor”(.02和.03)长度是相等,向下舍入就是.02, 如果是4.0251那么保留两位小数就是4.03。 */
package ext;
import java.text.DecimalFormat;
public class Text5 {
public static void main(String[]args){
System.out.println(new java.text.DecimalFormat("0.00").format(4.025));
System.out.println(new java.text.DecimalFormat("0.00").format(4.0251));
}
}
4.02
4.03
|