Here you can find the source of roundToSignificantDigits(double value, int n)
Parameter | Description |
---|---|
value | the value to round off. |
n | the number of significant decimal digits desired. |
public static double roundToSignificantDigits(double value, int n)
//package com.java2s; public class Main { private static final double TOLERANCE = 0.01; /**//w w w .j a v a 2s. c o m * Rounds a number to a given number of significant decimal digits. * Note that the number will be left with *only* this number of * significant digits regardless of magnitude, e.g. 12345 to 3 digits * will be 12300, whereas 0.12345 will be 0.123. * * @param value the value to round off. * @param n the number of significant decimal digits desired. * @return a rounded off number. */ public static double roundToSignificantDigits(double value, int n) { if (isEqual(value, 0.0)) { return 0.0; } final double d = Math .ceil(Math.log10(value < 0.0 ? -value : value)); final int power = n - (int) d; final double magnitude = Math.pow(10.0, power); final long shifted = Math.round(value * magnitude); return shifted / magnitude; } /** * Tests whether the two decimal numbers are equal with a tolerance of 0.01. * If one or both of the numbers are null, false is returned. * * @param d1 the first value. * @param d2 the second value. * @return true if the two decimal numbers are equal with a tolerance of 0.01. */ public static boolean isEqual(Double d1, Double d2) { if (d1 == null || d2 == null) { return false; } return Math.abs(d1 - d2) < TOLERANCE; } /** * Tests whether the two decimal numbers are equal with a tolerance of 0.01. * * @param d1 the first value. * @param d2 the second value. * @return true if the two decimal numbers are equal with a tolerance of 0.01. */ public static boolean isEqual(double d1, double d2) { return Math.abs(d1 - d2) < TOLERANCE; } }