samer@0: /* samer@0: * DoubleFormat.java samer@0: * samer@0: * Copyright (c) 2000, Samer Abdallah, King's College London. samer@0: * All rights reserved. samer@0: * samer@0: * This software is provided AS iS and WITHOUT ANY WARRANTY; samer@0: * without even the implied warranty of MERCHANTABILITY or samer@0: * FITNESS FOR A PARTICULAR PURPOSE. samer@0: */ samer@0: samer@0: package samer.core; samer@0: import java.text.*; samer@0: samer@0: public class DoubleFormat extends NumberFormat samer@0: { samer@0: int nfix=2; samer@0: samer@0: public DoubleFormat(int n) { setDecimals(n); } samer@0: samer@0: public void setDecimals(int n) { nfix=n; } samer@0: public String _format(double x) { return format(x,nfix); } samer@0: public double _parse(String s) { return Double.valueOf(s).doubleValue(); } samer@0: samer@0: samer@0: public StringBuffer format( long n, StringBuffer buf, FieldPosition fp) { samer@0: buf.append(n); samer@0: return buf; samer@0: } samer@0: public StringBuffer format( double x, StringBuffer buf, FieldPosition fp) { samer@0: buf.append(x); samer@0: return buf; samer@0: } samer@0: samer@0: public Number parse(String s, java.text.ParsePosition pp) { samer@0: return Double.valueOf(s); samer@0: } samer@0: // ............................................... samer@0: samer@0: public static String format( double x, int nfix) samer@0: { samer@0: int nfixPlus1=nfix+1; samer@0: // quick and dirty hack! samer@0: String s=Double.toString(x); samer@0: int point = s.indexOf('.'); samer@0: samer@0: // no decimals: return as is samer@0: if (point==-1) return s; samer@0: samer@0: // look for exponent samer@0: int exp = s.indexOf('E',point); samer@0: samer@0: if (exp==-1) { samer@0: // no exponent: count decimals samer@0: if (s.length()-point <= nfixPlus1) return s; samer@0: else { samer@0: // chop off excess precision samer@0: return s.substring(0,point+nfixPlus1); samer@0: } samer@0: } else { samer@0: // count digits up to exponent samer@0: if (exp-point < nfixPlus1) return s; samer@0: else { samer@0: // return truncated mantissa and exponent samer@0: return s.substring(0,point+nfixPlus1) + s.substring(exp); samer@0: } samer@0: } samer@0: } samer@0: }