annotate src/samer/core_/DoubleFormat.java @ 8:5e3cbbf173aa tip

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