001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.math3.fraction; 018 019import java.math.BigInteger; 020import java.text.FieldPosition; 021import java.text.NumberFormat; 022import java.text.ParsePosition; 023 024import org.apache.commons.math3.exception.util.LocalizedFormats; 025import org.apache.commons.math3.exception.NullArgumentException; 026 027/** 028 * Formats a BigFraction number in proper format. The number format for each of 029 * the whole number, numerator and, denominator can be configured. 030 * <p> 031 * Minus signs are only allowed in the whole number part - i.e., 032 * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and 033 * will result in a <code>ParseException</code>.</p> 034 * 035 * @since 1.1 036 */ 037public class ProperBigFractionFormat extends BigFractionFormat { 038 039 /** Serializable version identifier */ 040 private static final long serialVersionUID = -6337346779577272307L; 041 042 /** The format used for the whole number. */ 043 private NumberFormat wholeFormat; 044 045 /** 046 * Create a proper formatting instance with the default number format for 047 * the whole, numerator, and denominator. 048 */ 049 public ProperBigFractionFormat() { 050 this(getDefaultNumberFormat()); 051 } 052 053 /** 054 * Create a proper formatting instance with a custom number format for the 055 * whole, numerator, and denominator. 056 * @param format the custom format for the whole, numerator, and 057 * denominator. 058 */ 059 public ProperBigFractionFormat(final NumberFormat format) { 060 this(format, (NumberFormat)format.clone(), (NumberFormat)format.clone()); 061 } 062 063 /** 064 * Create a proper formatting instance with a custom number format for each 065 * of the whole, numerator, and denominator. 066 * @param wholeFormat the custom format for the whole. 067 * @param numeratorFormat the custom format for the numerator. 068 * @param denominatorFormat the custom format for the denominator. 069 */ 070 public ProperBigFractionFormat(final NumberFormat wholeFormat, 071 final NumberFormat numeratorFormat, 072 final NumberFormat denominatorFormat) { 073 super(numeratorFormat, denominatorFormat); 074 setWholeFormat(wholeFormat); 075 } 076 077 /** 078 * Formats a {@link BigFraction} object to produce a string. The BigFraction 079 * is output in proper format. 080 * 081 * @param fraction the object to format. 082 * @param toAppendTo where the text is to be appended 083 * @param pos On input: an alignment field, if desired. On output: the 084 * offsets of the alignment field 085 * @return the value passed in as toAppendTo. 086 */ 087 @Override 088 public StringBuffer format(final BigFraction fraction, 089 final StringBuffer toAppendTo, final FieldPosition pos) { 090 091 pos.setBeginIndex(0); 092 pos.setEndIndex(0); 093 094 BigInteger num = fraction.getNumerator(); 095 BigInteger den = fraction.getDenominator(); 096 BigInteger whole = num.divide(den); 097 num = num.remainder(den); 098 099 if (!BigInteger.ZERO.equals(whole)) { 100 getWholeFormat().format(whole, toAppendTo, pos); 101 toAppendTo.append(' '); 102 if (num.compareTo(BigInteger.ZERO) < 0) { 103 num = num.negate(); 104 } 105 } 106 getNumeratorFormat().format(num, toAppendTo, pos); 107 toAppendTo.append(" / "); 108 getDenominatorFormat().format(den, toAppendTo, pos); 109 110 return toAppendTo; 111 } 112 113 /** 114 * Access the whole format. 115 * @return the whole format. 116 */ 117 public NumberFormat getWholeFormat() { 118 return wholeFormat; 119 } 120 121 /** 122 * Parses a string to produce a {@link BigFraction} object. This method 123 * expects the string to be formatted as a proper BigFraction. 124 * <p> 125 * Minus signs are only allowed in the whole number part - i.e., 126 * "-3 1/2" is legitimate and denotes -7/2, but "-3 -1/2" is invalid and 127 * will result in a <code>ParseException</code>.</p> 128 * 129 * @param source the string to parse 130 * @param pos input/ouput parsing parameter. 131 * @return the parsed {@link BigFraction} object. 132 */ 133 @Override 134 public BigFraction parse(final String source, final ParsePosition pos) { 135 // try to parse improper BigFraction 136 BigFraction ret = super.parse(source, pos); 137 if (ret != null) { 138 return ret; 139 } 140 141 final int initialIndex = pos.getIndex(); 142 143 // parse whitespace 144 parseAndIgnoreWhitespace(source, pos); 145 146 // parse whole 147 BigInteger whole = parseNextBigInteger(source, pos); 148 if (whole == null) { 149 // invalid integer number 150 // set index back to initial, error index should already be set 151 // character examined. 152 pos.setIndex(initialIndex); 153 return null; 154 } 155 156 // parse whitespace 157 parseAndIgnoreWhitespace(source, pos); 158 159 // parse numerator 160 BigInteger num = parseNextBigInteger(source, pos); 161 if (num == null) { 162 // invalid integer number 163 // set index back to initial, error index should already be set 164 // character examined. 165 pos.setIndex(initialIndex); 166 return null; 167 } 168 169 if (num.compareTo(BigInteger.ZERO) < 0) { 170 // minus signs should be leading, invalid expression 171 pos.setIndex(initialIndex); 172 return null; 173 } 174 175 // parse '/' 176 final int startIndex = pos.getIndex(); 177 final char c = parseNextCharacter(source, pos); 178 switch (c) { 179 case 0 : 180 // no '/' 181 // return num as a BigFraction 182 return new BigFraction(num); 183 case '/' : 184 // found '/', continue parsing denominator 185 break; 186 default : 187 // invalid '/' 188 // set index back to initial, error index should be the last 189 // character examined. 190 pos.setIndex(initialIndex); 191 pos.setErrorIndex(startIndex); 192 return null; 193 } 194 195 // parse whitespace 196 parseAndIgnoreWhitespace(source, pos); 197 198 // parse denominator 199 final BigInteger den = parseNextBigInteger(source, pos); 200 if (den == null) { 201 // invalid integer number 202 // set index back to initial, error index should already be set 203 // character examined. 204 pos.setIndex(initialIndex); 205 return null; 206 } 207 208 if (den.compareTo(BigInteger.ZERO) < 0) { 209 // minus signs must be leading, invalid 210 pos.setIndex(initialIndex); 211 return null; 212 } 213 214 boolean wholeIsNeg = whole.compareTo(BigInteger.ZERO) < 0; 215 if (wholeIsNeg) { 216 whole = whole.negate(); 217 } 218 num = whole.multiply(den).add(num); 219 if (wholeIsNeg) { 220 num = num.negate(); 221 } 222 223 return new BigFraction(num, den); 224 225 } 226 227 /** 228 * Modify the whole format. 229 * @param format The new whole format value. 230 * @throws NullArgumentException if {@code format} is {@code null}. 231 */ 232 public void setWholeFormat(final NumberFormat format) { 233 if (format == null) { 234 throw new NullArgumentException(LocalizedFormats.WHOLE_FORMAT); 235 } 236 this.wholeFormat = format; 237 } 238}