private String formatCoef ( double coef ) { double tol = 1e-6 ; // rounding tolerance // zero case if ( Math . abs ( coef ) < tol ) { return "0" ; } // integer case long num = Math . round ( coef ) ; if ( Math . abs ( num - coef ) < tol ) { return Long . toString ( num ) ; } // Other small cases for ( int denom = 2 ; denom < 12 ; denom ++ ) { num = Math . round ( coef * denom ) ; if ( num - coef * denom < tol ) { return String . format ( "%d/%d" , num , denom ) ; } } // Give up and use floating point; return String . format ( "%.3f" , coef ) ; }
helper function to format simple fractions into rationals