Java tutorial
//package com.java2s; public class Main { /** * Returns the appropriate number of decimals to be used for the provided * number. * * @param number * @return */ public static int getDecimals(float number) { float i = roundToNextSignificant(number); return (int) Math.ceil(-Math.log10(i)) + 2; } /** * rounds the given number to the next significant number * * @param number * @return */ public static float roundToNextSignificant(double number) { final float d = (float) Math.ceil((float) Math.log10(number < 0 ? -number : number)); final int pw = 1 - (int) d; final float magnitude = (float) Math.pow(10, pw); final long shifted = Math.round(number * magnitude); return shifted / magnitude; } }