保留小数小功能的测试
package test;
import java.text.DecimalFormat;
public class TestDouble {
/**
* 测试 保留小数的方式:
* 注意:保留小数时 尽量慎用 String.subStr(startIndex,endIndex),当String的有效长度小于endIndex时,会出现异常信息。
* @paramargs
*/
public static void main(String[] args) {
}
/**
* 通过 Decimal的格式化 来保留小数
* @return
*/
public String method1(){
DecimalFormat format = new DecimalFormat("0.00");
double a = 22;
double b = 33;
double f = a/b;
System.out.println(a/b);
System.out.println(format.format(f));
String s= format.format(f);
return s;
}
/**
* 方式二: 通过String 的方式来 保留小数
*/
/**
* 注意 : JUnit测试不能有 返回值 ,必须是void 修饰
* @return
*/
@org.junit.Test
public void method2(){
double a = 2;
double b = 3;
double result = a/b;//这是个无限小数
//%.2f %.表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型
//System.out.println(String.format("%.2f", d));
String aa = String.valueOf(result);
System.out.println(aa);
System.out.println(String.format("%.2f", result));
}
/**
* 方式三 : 通过 String.subStr(startIndex,endIndex) 来保留小数
* 小数点也是一位数
* 注意:subStr方法的使用, 当endIndex的下标大于 小小数的有效昌都时,会出现报错信息
* java.lang.StringIndexOutOfBoundsException: String index out of range: 4
*/
@org.junit.Test
public void methods3(){
double a = 2;
double b = 3;
double result = a/b;//这是个无线小数
String aa = String.valueOf(result);
System.out.println(aa.substring(0, 5));
double c = 1;
double d = 1;
double result2 = c/d; //结果为 1.0 ,截取4位有效数字则会出现报错信息
System.out.println(String.valueOf(result2).substring(0,4));
}
}