java保留截取⼩数点后23456位⼩数
⼩数点后保留六位⼩数的⼏种⽅法
public static void main(String[] args) {
nf.setMaximumFractionDigits(6);//保留⼩数点后⼏位就传⼏
nf.setRoundingMode(RoundingMode.DOWN);//需要四舍五⼊就⽤ RoundingMode.UP
double lat = 120.15784662032509;
/**
* und() “四舍五⼊”,该函数返回的是⼀个四舍五⼊后的的整数
bigdecimal除法保留小数
* il()  “向上取整”,即⼩数部分直接舍去,并向正数部分进1
* Math.floor() “向下取整” ,即⼩数部分直接舍去
*/
}
由于我处理的是经纬度需要保留⼩数点后六位数,有些就不适⽤了。
ps:今天再测试的时候发现 NumberFormat处理经度时总会出现取五位的情况,是因为如果截取的最后⼀位是0的话在格式化的时候会不显⽰出来。最后只能⾃⼰使⽤subString⾃⼰截取了。
public static void main(String[] args) {
//nf = (DecimalFormat)nf;
((DecimalFormat) nf).applyPattern("#.000000");//强制转换为DecimalFormat 添加格式
nf.setMaximumFractionDigits(6);//保留⼩数点后⼏位就传⼏
nf.setRoundingMode(RoundingMode.DOWN);//需要四舍五⼊就⽤ RoundingMode.UP
}
public static String SubStringLaLotude(Double number) {
String strLanlot="0.000000";
if(number>0){
strLanlot = String.valueOf(number);
// 获得第⼀个点的位置
int index = strLanlot.indexOf(".");
// 根据点的位置,截取字符串。得到结果 result
String result = strLanlot.substring(index);
strLanlot = strLanlot.substring(0, index) + (result.length() < 7 ? result : result.substring(0, 7));// 取⼩数点后六位的经纬度
}
return strLanlot;
}
public class DoubleFormat {
double f = 11.4585;
public void m1() {
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
}
/**
* DecimalFormat转换最简便
*/
public void m2() {
//#.00 表⽰两位⼩数
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println(df.format(f));
}
/**
* String.format打印最简便
*/
public void m3() {
//%.2f  %.表⽰⼩数点前任意位数  2 表⽰两位⼩数格式后的结果为f 表⽰浮点型
System.out.println(String.format("%.2f", f));
}
public void m4() {
NumberFormat nf = NumberInstance();
/
/digits 显⽰的数字位数为格式化对象设定⼩数点后的显⽰的最多位,显⽰的最后位是舍⼊的        nf.setMaximumFractionDigits(2);
System.out.println(nf.format(f));
}
public static void main(String[] args) {
DoubleFormat f = new DoubleFormat();
f.m1();
f.m2();
f.m3();
f.m4();
}
/*      Math.floor()  通过该函数计算后的返回值是舍去⼩数点后的数值
如:Math.floor(3.2)返回3
Math.floor(3.9)返回3
Math.floor(3.0)返回3
ceil函数只要⼩数点⾮0,将返回整数部分+1
如:il(3.2)返回4
}