2
* This program is free software; you can redistribute it and/or modify
3
* it under the terms of the GNU General Public License as published by
4
* the Free Software Foundation; either version 2 of the License, or (at
5
* your option) any later version.
7
* This program is distributed in the hope that it will be useful, but
8
* WITHOUT ANY WARRANTY; without even the implied warranty of
9
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10
* General Public License for more details.
12
* You should have received a copy of the GNU General Public License
13
* along with this program; if not, write to the Free Software
14
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18
* Copyright (C) 2002 University of Waikato, Hamilton, New Zealand
22
package weka.core.matrix;
24
import java.text.DecimalFormat;
25
import java.text.FieldPosition;
28
* Class for the format of floating point numbers
31
* @version $Revision: 1.3 $
33
public class FloatingPointFormat
34
extends DecimalFormat {
36
/** for serialization */
37
private static final long serialVersionUID = 4500373755333429499L;
39
protected DecimalFormat nf ;
41
protected int decimal;
42
protected boolean trailing = true;
47
public FloatingPointFormat () {
51
public FloatingPointFormat ( int digits ) {
55
public FloatingPointFormat( int w, int d ) {
58
nf = new DecimalFormat( pattern(w, d) );
59
nf.setPositivePrefix(" ");
60
nf.setNegativePrefix("-");
63
public FloatingPointFormat( int w, int d, boolean trailingZeros ) {
65
this.trailing = trailingZeros;
68
public StringBuffer format(double number, StringBuffer toAppendTo,
70
StringBuffer s = new StringBuffer( nf.format(number) );
71
if( s.length() > width ) {
72
if( s.charAt(0) == ' ' && s.length() == width + 1 ) {
77
for( int i = 0; i < width; i ++ )
82
for (int i = 0; i < width - s.length(); i++) // padding
85
if( !trailing && decimal > 0 ) { // delete trailing zeros
86
while( s.charAt( s.length()-1 ) == '0' )
87
s.deleteCharAt( s.length()-1 );
88
if( s.charAt( s.length()-1 ) == '.' )
89
s.deleteCharAt( s.length()-1 );
92
return toAppendTo.append( s );
95
public static String pattern( int w, int d ) {
96
StringBuffer s = new StringBuffer(); // "-##0.00" // fw.d
97
s.append( padding(w - d - 3, '#') );
98
if( d == 0) s.append('0');
101
s.append( padding( d, '0') );
106
private static StringBuffer padding( int n, char c ) {
107
StringBuffer text = new StringBuffer();
109
for(int i = 0; i < n; i++ ){
116
public int width () {
117
if( !trailing ) throw new RuntimeException( "flexible width" );