import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.junit.Test;
public class Keep2point {
@Test
public void test1() {//使用NumberFormat类
double x=23.5455;
NumberFormat nf=NumberFormat.getNumberInstance() ;
nf.setMaximumFractionDigits(2);
String s= nf.format(x) ;
System.out.println(s);
}
@Test
public void test2() {//使用BigDecimal类
double n = 12345.643;
BigDecimal bd = new BigDecimal(n);
double n1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//四舍五入,最多保留两位小数
System.out.println(n1);
}
@Test
public void test3() {//使用DecimalFormat类
/*
* DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字
*/
DecimalFormat df = new DecimalFormat("#.##");// 四舍五入的方式,最多保留两位小数
DecimalFormat df1 = new DecimalFormat("#.00");//四舍五入的方式,保留两位小数
double n1 = 123.1255;
double n2 = 3.2;
double n3 = 1255;
System.out.println(df.format(n1));
System.out.println(df.format(n2));
System.out.println(df.format(n3));
System.out.println(df1.format(n1));
System.out.println(df1.format(n2));
System.out.println(df1.format(n3));
/*
* 输出的结果:
* 123.13
* 3.2
* 1255
*
* 123.13
* 3.20
* 1255.00
*/
}
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.junit.Test;
public class Keep2point {
@Test
public void test1() {//使用NumberFormat类
double x=23.5455;
NumberFormat nf=NumberFormat.getNumberInstance() ;
nf.setMaximumFractionDigits(2);
String s= nf.format(x) ;
System.out.println(s);
}
@Test
public void test2() {//使用BigDecimal类
double n = 12345.643;
BigDecimal bd = new BigDecimal(n);
double n1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//四舍五入,最多保留两位小数
System.out.println(n1);
}
@Test
public void test3() {//使用DecimalFormat类
/*
* DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字
*/
DecimalFormat df = new DecimalFormat("#.##");// 四舍五入的方式,最多保留两位小数
DecimalFormat df1 = new DecimalFormat("#.00");//四舍五入的方式,保留两位小数
double n1 = 123.1255;
double n2 = 3.2;
double n3 = 1255;
System.out.println(df.format(n1));
System.out.println(df.format(n2));
System.out.println(df.format(n3));
System.out.println(df1.format(n1));
System.out.println(df1.format(n2));
System.out.println(df1.format(n3));
/*
* 输出的结果:
* 123.13
* 3.2
* 1255
*
* 123.13
* 3.20
* 1255.00
*/
}