Here you can find the source of roundToNumDigits(double d, int n)
Parameter | Description |
---|---|
d | The number to round |
n | The number of digits to round to |
public static double roundToNumDigits(double d, int n)
//package com.java2s; //License from project: Open Source License public class Main { /**/*from ww w .jav a2 s . c o m*/ * Rounds the input double to n significant digits. This code started from * an example on * http://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits * * @param d The number to round * @param n The number of digits to round to * @return d rounded to n digits */ public static double roundToNumDigits(double d, int n) { if (d == 0) { return 0; } final long numDs = mostSignificantDigitPosition(d); final long power = n - ((numDs > 0) ? numDs : (numDs + 1)); final double mag = Math.pow(10, power); final long shifted = Math.round(d * mag); return shifted / mag; } /** * Returns the position of the most significant digit of d. * * @param d The number to test for position of most significant digit * @return the position of the most significant digit */ public static long mostSignificantDigitPosition(double d) { double nDigits = Math.log10(Math.abs(d)); if ((nDigits == (int) nDigits) && (nDigits >= 0)) { nDigits += 1; } return (d == 0) ? 0 : (nDigits > 0) ? (long) Math.ceil(nDigits) : (long) Math.floor(nDigits); } }