Here you can find the source of roundToSignificantDigits(double x, double y, int nSignif)
public static Double[] roundToSignificantDigits(double x, double y, int nSignif)
//package com.java2s; //License from project: Open Source License public class Main { /** Function to round x and y to a number of digits enough to show the difference in range * This is for pretty printing only. * */// w w w .j a v a2s.c o m public static Double[] roundToSignificantDigits(double x, double y, int nSignif) { Double[] rounded = new Double[2]; double diff = Math.abs(x - y); if (diff < 1e-16) { rounded[0] = x; rounded[1] = y; return rounded; } if (diff > 1) { // Round to 2 digits regardless of how large is the diff rounded[0] = Math.rint(x * Math.pow(10.0, nSignif)) / Math.pow(10.0, nSignif); rounded[1] = Math.rint(y * Math.pow(10.0, nSignif)) / Math.pow(10.0, nSignif); return rounded; } else { // Diff is small, < 1. See how many digits you need to approximate // Get number of leading zeros int nzeros = (int) (Math.ceil(Math.abs(Math.log10(diff))) + nSignif); rounded[0] = Math.rint(x * Math.pow(10.0, nzeros)) / Math.pow(10.0, nzeros); rounded[1] = Math.rint(y * Math.pow(10.0, nzeros)) / Math.pow(10.0, nzeros); return rounded; } } }