Java tutorial
//package com.java2s; //License from project: Open Source License public class Main { public static String getSigFig(double value, int n) { String result = String.format("%.10f", value); int k = (int) (Math.log(Math.abs(value)) / Math.log(10)); if ((k + 1) >= n) { // Assume value > 0 result = result.substring(0, n); } else { if (value < 0) { n = n + 1; } if (0 < Math.abs(value) && Math.abs(value) < 1) { n = n + 1; } if (value != 0) { result = result.substring(0, n + 1); } else { n = n + 2; result = "0.0"; } // Add trailing zeros while (result.length() < n) { result = result + "0"; } } return result; } public static String[] getSigFig(double[] values, int n) { String[] result = new String[values.length]; for (int i = 0; i < values.length; i++) { result[i] = getSigFig(values[i], n); } return result; } }