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