Here you can find the source of roundString(double d)
public static String roundString(double d)
//package com.java2s; //License from project: Open Source License public class Main { /** Rounds the number returning a string representation of the numner */ public static String roundString(double d) { if (d == 0.0) return "" + d; int digits = (int) (Math.log(d) / Math.log(10)); int n = 3 - digits; return fixBug("" + round(d, n), n); }//ww w. j a v a2s . co m public static String roundString(double d, int n) { return fixBug("" + round(d, n), n); } private static String fixBug(String s, int n) { if (n >= 3) { int dotIndex = s.indexOf('.'); if (dotIndex != -1) while ((s.charAt(s.length() - 1) == '0') && dotIndex < s.length() - 2) s = s.substring(0, s.length() - 1); } // Remove the .0 part if n == 0 if (n == 0) { return s.substring(0, s.indexOf(".")); } return s; } /** Rounds the number to 4 significant digits */ public static double round(double d) { if (d == 0.0) return d; int digits = (int) (Math.log(d) / Math.log(10)); return round(d, 3 - digits); } /** Rounds the number to n decimal places */ public static double round(double d, int n) { double shift = Math.pow(10, n); return ((double) ((long) (d * shift + 0.5))) / shift; } }