Here you can find the source of formatDouble(double num)
Parameter | Description |
---|---|
num | a parameter |
public static double formatDouble(double num)
//package com.java2s; //License from project: Open Source License import java.text.DecimalFormat; public class Main { /**/* w w w .j ava 2 s . co m*/ * b.try to format double number with 3 digit precision by default * * @param num * @return */ public static double[] formatDouble(double[] num) { double[] q = new double[num.length]; for (int i = 0; i < num.length; i++) { q[i] = formatDouble(num[i]); } return q; } /** * b.try to format double number with 3 digit precision by default * * @param num * @return */ public static double[][] formatDouble(double[][] num) { double[][] q = new double[num.length][num[0].length]; for (int i = 0; i < num.length; i++) { for (int j = 0; j < num[0].length; j++) { q[i][j] = formatDouble(num[i][j]); } } return q; } /** * b.try to format double numer with n digit precision by default * * @param num * @return */ public static double[] formatDouble(double[] num, int n) { double[] q = new double[num.length]; for (int i = 0; i < num.length; i++) { q[i] = formatDouble(num[i], n); } return q; } /** * b.try to format double number with 3 digit precision by default * * @param num * @return */ public static double formatDouble(double num) { double q = 0; try { DecimalFormat df = new DecimalFormat("#.000"); q = Double.parseDouble(df.format(num).replace(",", ".")); } catch (Exception e) { // e.printStackTrace(); return -10000000000000.0; } return q; } public static double formatDouble(double num, int n) { double q = 0; try { DecimalFormat df = null; switch (n) { case 0: return Math.floor(num); case 1: df = new DecimalFormat("#.0"); break; case 2: df = new DecimalFormat("#.00"); break; case 3: df = new DecimalFormat("#.000"); break; case 4: df = new DecimalFormat("#.0000"); break; case 5: df = new DecimalFormat("#.00000"); break; default: df = new DecimalFormat("#.000"); break; } // DecimalFormat df = new DecimalFormat("#.###"); q = Double.parseDouble(df.format(num).replace(",", ".")); } catch (Exception e) { // e.printStackTrace(); return 0; } return q; } }