comparison src/samer/core_/DoubleFormat.java @ 0:bf79fb79ee13

Initial Mercurial check in.
author samer
date Tue, 17 Jan 2012 17:50:20 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:bf79fb79ee13
1 /*
2 * DoubleFormat.java
3 *
4 * Copyright (c) 2000, Samer Abdallah, King's College London.
5 * All rights reserved.
6 *
7 * This software is provided AS iS and WITHOUT ANY WARRANTY;
8 * without even the implied warranty of MERCHANTABILITY or
9 * FITNESS FOR A PARTICULAR PURPOSE.
10 */
11
12 package samer.core;
13 import java.text.*;
14
15 public class DoubleFormat extends NumberFormat
16 {
17 int nfix=2;
18
19 public DoubleFormat(int n) { setDecimals(n); }
20
21 public void setDecimals(int n) { nfix=n; }
22 public String _format(double x) { return format(x,nfix); }
23 public double _parse(String s) { return Double.valueOf(s).doubleValue(); }
24
25
26 public StringBuffer format( long n, StringBuffer buf, FieldPosition fp) {
27 buf.append(n);
28 return buf;
29 }
30 public StringBuffer format( double x, StringBuffer buf, FieldPosition fp) {
31 buf.append(x);
32 return buf;
33 }
34
35 public Number parse(String s, java.text.ParsePosition pp) {
36 return Double.valueOf(s);
37 }
38 // ...............................................
39
40 public static String format( double x, int nfix)
41 {
42 int nfixPlus1=nfix+1;
43 // quick and dirty hack!
44 String s=Double.toString(x);
45 int point = s.indexOf('.');
46
47 // no decimals: return as is
48 if (point==-1) return s;
49
50 // look for exponent
51 int exp = s.indexOf('E',point);
52
53 if (exp==-1) {
54 // no exponent: count decimals
55 if (s.length()-point <= nfixPlus1) return s;
56 else {
57 // chop off excess precision
58 return s.substring(0,point+nfixPlus1);
59 }
60 } else {
61 // count digits up to exponent
62 if (exp-point < nfixPlus1) return s;
63 else {
64 // return truncated mantissa and exponent
65 return s.substring(0,point+nfixPlus1) + s.substring(exp);
66 }
67 }
68 }
69 }