小數點后保留六位小數的幾種方法
public static void main(String[] args) { java.text.DecimalFormat df = new DecimalFormat("#.000000"); java.text.NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(6);//保留小數點后幾位就傳幾 nf.setRoundingMode(RoundingMode.DOWN);//需要四舍五入就用 RoundingMode.UP double lat = 120.15784662032509; System.err.println(df.format(lat));//1 System.err.println(nf.format(lat));//2 System.err.println(String.format("%.6f",lat));//3 System.err.println(df.format((int) Math.ceil(lat)));//向上取整 /** * Math.round() “四舍五入”, 該函數返回的是一個四舍五入后的的整數 * Math.ceil() “向上取整”, 即小數部分直接舍去,並向正數部分進1 * Math.floor() “向下取整” ,即小數部分直接舍去 */ }
由於我處理的是經緯度需要保留小數點后六位數,有些就不適用了。
ps:今天再測試的時候發現 NumberFormat處理經度時總會出現取五位的情況,是因為如果截取的最后一位是0的話在格式化的時候會不顯示出來。最后只能自己使用subString自己截取了。
public static void main(String[] args) { java.text.NumberFormat nf = NumberFormat.getNumberInstance(); //nf = (DecimalFormat)nf; ((DecimalFormat) nf).applyPattern("#.000000");//強制轉換為DecimalFormat 添加格式 nf.setMaximumFractionDigits(6);//保留小數點后幾位就傳幾 nf.setRoundingMode(RoundingMode.DOWN);//需要四舍五入就用 RoundingMode.UP System.err.println(nf.format(136.54222032402261));// System.err.println(nf.format(29.939281970523797));// System.err.println(SubStringLaLotude(136.54222032402261));// } 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; }
有關其他的數字處理可以參考下 :https://blog.csdn.net/a1064072510/article/details/89887633
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 = NumberFormat.getNumberInstance(); //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 Math.ceil() ceil函數只要小數點非0,將返回整數部分+1 如:Math.ceil(3.2)返回4 Math.ceil(3.9)返回4 Math.ceil(3.0)返回3*/ }