Java Number Round roundString(double d)

Here you can find the source of roundString(double d)

Description

Rounds the number returning a string representation of the numner

License

Open Source License

Declaration

public static String roundString(double d) 

Method Source Code

//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;
    }
}

Related

  1. roundSimpleNumberUnits(final long graphDefaultUnit)
  2. roundSizes(float[] sizes)
  3. roundSonekiSuii(double amount1, double amount2)
  4. roundsToTicks(double x)
  5. roundStr(Double value, int decimal)
  6. roundString(double n, double range, double precision)
  7. roundTime24h(final long defaultUnitValue)
  8. roundTimeStamp(long tstamp)
  9. roundTimeValue(final float defaultUnitValue, final boolean is24HourFormatting)