Path: blob/master/src/java.base/share/classes/java/text/DigitList.java
41152 views
/*1* Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved27* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved28*29* The original version of this source code and documentation is copyrighted30* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These31* materials are provided under terms of a License Agreement between Taligent32* and Sun. This technology is protected by multiple US and International33* patents. This notice and attribution to Taligent may not be removed.34* Taligent is a registered trademark of Taligent, Inc.35*36*/3738package java.text;3940import java.math.BigDecimal;41import java.math.BigInteger;42import java.math.RoundingMode;43import jdk.internal.math.FloatingDecimal;4445/**46* Digit List. Private to DecimalFormat.47* Handles the transcoding48* between numeric values and strings of characters. Only handles49* non-negative numbers. The division of labor between DigitList and50* DecimalFormat is that DigitList handles the radix 10 representation51* issues; DecimalFormat handles the locale-specific issues such as52* positive/negative, grouping, decimal point, currency, and so on.53*54* A DigitList is really a representation of a floating point value.55* It may be an integer value; we assume that a double has sufficient56* precision to represent all digits of a long.57*58* The DigitList representation consists of a string of characters,59* which are the digits radix 10, from '0' to '9'. It also has a radix60* 10 exponent associated with it. The value represented by a DigitList61* object can be computed by mulitplying the fraction f, where 0 <= f < 1,62* derived by placing all the digits of the list to the right of the63* decimal point, by 10^exponent.64*65* @see Locale66* @see Format67* @see NumberFormat68* @see DecimalFormat69* @see ChoiceFormat70* @see MessageFormat71* @author Mark Davis, Alan Liu72*/73final class DigitList implements Cloneable {74/**75* The maximum number of significant digits in an IEEE 754 double, that76* is, in a Java double. This must not be increased, or garbage digits77* will be generated, and should not be decreased, or accuracy will be lost.78*/79public static final int MAX_COUNT = 19; // == Long.toString(Long.MAX_VALUE).length()8081/**82* These data members are intentionally public and can be set directly.83*84* The value represented is given by placing the decimal point before85* digits[decimalAt]. If decimalAt is < 0, then leading zeros between86* the decimal point and the first nonzero digit are implied. If decimalAt87* is > count, then trailing zeros between the digits[count-1] and the88* decimal point are implied.89*90* Equivalently, the represented value is given by f * 10^decimalAt. Here91* f is a value 0.1 <= f < 1 arrived at by placing the digits in Digits to92* the right of the decimal.93*94* DigitList is normalized, so if it is non-zero, figits[0] is non-zero. We95* don't allow denormalized numbers because our exponent is effectively of96* unlimited magnitude. The count value contains the number of significant97* digits present in digits[].98*99* Zero is represented by any DigitList with count == 0 or with each digits[i]100* for all i <= count == '0'.101*/102public int decimalAt = 0;103public int count = 0;104public char[] digits = new char[MAX_COUNT];105106private char[] data;107private RoundingMode roundingMode = RoundingMode.HALF_EVEN;108private boolean isNegative = false;109110/**111* Return true if the represented number is zero.112*/113boolean isZero() {114for (int i=0; i < count; ++i) {115if (digits[i] != '0') {116return false;117}118}119return true;120}121122/**123* Set the rounding mode124*/125void setRoundingMode(RoundingMode r) {126roundingMode = r;127}128129/**130* Clears out the digits.131* Use before appending them.132* Typically, you set a series of digits with append, then at the point133* you hit the decimal point, you set myDigitList.decimalAt = myDigitList.count;134* then go on appending digits.135*/136public void clear () {137decimalAt = 0;138count = 0;139}140141/**142* Appends a digit to the list, extending the list when necessary.143*/144public void append(char digit) {145if (count == digits.length) {146char[] data = new char[count + 100];147System.arraycopy(digits, 0, data, 0, count);148digits = data;149}150digits[count++] = digit;151}152153/**154* Utility routine to get the value of the digit list155* If (count == 0) this throws a NumberFormatException, which156* mimics Long.parseLong().157*/158public final double getDouble() {159if (count == 0) {160return 0.0;161}162163StringBuffer temp = getStringBuffer();164temp.append('.');165temp.append(digits, 0, count);166temp.append('E');167temp.append(decimalAt);168return Double.parseDouble(temp.toString());169}170171/**172* Utility routine to get the value of the digit list.173* If (count == 0) this returns 0, unlike Long.parseLong().174*/175public final long getLong() {176// for now, simple implementation; later, do proper IEEE native stuff177178if (count == 0) {179return 0;180}181182// We have to check for this, because this is the one NEGATIVE value183// we represent. If we tried to just pass the digits off to parseLong,184// we'd get a parse failure.185if (isLongMIN_VALUE()) {186return Long.MIN_VALUE;187}188189StringBuffer temp = getStringBuffer();190temp.append(digits, 0, count);191for (int i = count; i < decimalAt; ++i) {192temp.append('0');193}194return Long.parseLong(temp.toString());195}196197public final BigDecimal getBigDecimal() {198if (count == 0) {199if (decimalAt == 0) {200return BigDecimal.ZERO;201} else {202return new BigDecimal("0E" + decimalAt);203}204}205206if (decimalAt == count) {207return new BigDecimal(digits, 0, count);208} else {209return new BigDecimal(digits, 0, count).scaleByPowerOfTen(decimalAt - count);210}211}212213/**214* Return true if the number represented by this object can fit into215* a long.216* @param isPositive true if this number should be regarded as positive217* @param ignoreNegativeZero true if -0 should be regarded as identical to218* +0; otherwise they are considered distinct219* @return true if this number fits into a Java long220*/221boolean fitsIntoLong(boolean isPositive, boolean ignoreNegativeZero) {222// Figure out if the result will fit in a long. We have to223// first look for nonzero digits after the decimal point;224// then check the size. If the digit count is 18 or less, then225// the value can definitely be represented as a long. If it is 19226// then it may be too large.227228// Trim trailing zeros. This does not change the represented value.229while (count > 0 && digits[count - 1] == '0') {230--count;231}232233if (count == 0) {234// Positive zero fits into a long, but negative zero can only235// be represented as a double. - bug 4162852236return isPositive || ignoreNegativeZero;237}238239if (decimalAt < count || decimalAt > MAX_COUNT) {240return false;241}242243if (decimalAt < MAX_COUNT) return true;244245// At this point we have decimalAt == count, and count == MAX_COUNT.246// The number will overflow if it is larger than 9223372036854775807247// or smaller than -9223372036854775808.248for (int i=0; i<count; ++i) {249char dig = digits[i], max = LONG_MIN_REP[i];250if (dig > max) return false;251if (dig < max) return true;252}253254// At this point the first count digits match. If decimalAt is less255// than count, then the remaining digits are zero, and we return true.256if (count < decimalAt) return true;257258// Now we have a representation of Long.MIN_VALUE, without the leading259// negative sign. If this represents a positive value, then it does260// not fit; otherwise it fits.261return !isPositive;262}263264/**265* Set the digit list to a representation of the given double value.266* This method supports fixed-point notation.267* @param isNegative Boolean value indicating whether the number is negative.268* @param source Value to be converted; must not be Inf, -Inf, Nan,269* or a value <= 0.270* @param maximumFractionDigits The most fractional digits which should271* be converted.272*/273final void set(boolean isNegative, double source, int maximumFractionDigits) {274set(isNegative, source, maximumFractionDigits, true);275}276277/**278* Set the digit list to a representation of the given double value.279* This method supports both fixed-point and exponential notation.280* @param isNegative Boolean value indicating whether the number is negative.281* @param source Value to be converted; must not be Inf, -Inf, Nan,282* or a value <= 0.283* @param maximumDigits The most fractional or total digits which should284* be converted.285* @param fixedPoint If true, then maximumDigits is the maximum286* fractional digits to be converted. If false, total digits.287*/288final void set(boolean isNegative, double source, int maximumDigits, boolean fixedPoint) {289290FloatingDecimal.BinaryToASCIIConverter fdConverter = FloatingDecimal.getBinaryToASCIIConverter(source);291boolean hasBeenRoundedUp = fdConverter.digitsRoundedUp();292boolean valueExactAsDecimal = fdConverter.decimalDigitsExact();293assert !fdConverter.isExceptional();294String digitsString = fdConverter.toJavaFormatString();295296set(isNegative, digitsString,297hasBeenRoundedUp, valueExactAsDecimal,298maximumDigits, fixedPoint);299}300301/**302* Generate a representation of the form DDDDD, DDDDD.DDDDD, or303* DDDDDE+/-DDDDD.304* @param roundedUp whether or not rounding up has already happened.305* @param valueExactAsDecimal whether or not collected digits provide306* an exact decimal representation of the value.307*/308private void set(boolean isNegative, String s,309boolean roundedUp, boolean valueExactAsDecimal,310int maximumDigits, boolean fixedPoint) {311312this.isNegative = isNegative;313int len = s.length();314char[] source = getDataChars(len);315s.getChars(0, len, source, 0);316317decimalAt = -1;318count = 0;319int exponent = 0;320// Number of zeros between decimal point and first non-zero digit after321// decimal point, for numbers < 1.322int leadingZerosAfterDecimal = 0;323boolean nonZeroDigitSeen = false;324325for (int i = 0; i < len; ) {326char c = source[i++];327if (c == '.') {328decimalAt = count;329} else if (c == 'e' || c == 'E') {330exponent = parseInt(source, i, len);331break;332} else {333if (!nonZeroDigitSeen) {334nonZeroDigitSeen = (c != '0');335if (!nonZeroDigitSeen && decimalAt != -1)336++leadingZerosAfterDecimal;337}338if (nonZeroDigitSeen) {339digits[count++] = c;340}341}342}343if (decimalAt == -1) {344decimalAt = count;345}346if (nonZeroDigitSeen) {347decimalAt += exponent - leadingZerosAfterDecimal;348}349350if (fixedPoint) {351// The negative of the exponent represents the number of leading352// zeros between the decimal and the first non-zero digit, for353// a value < 0.1 (e.g., for 0.00123, -decimalAt == 2). If this354// is more than the maximum fraction digits, then we have an underflow355// for the printed representation.356if (-decimalAt > maximumDigits) {357// Handle an underflow to zero when we round something like358// 0.0009 to 2 fractional digits.359count = 0;360return;361} else if (-decimalAt == maximumDigits) {362// If we round 0.0009 to 3 fractional digits, then we have to363// create a new one digit in the least significant location.364if (shouldRoundUp(0, roundedUp, valueExactAsDecimal)) {365count = 1;366++decimalAt;367digits[0] = '1';368} else {369count = 0;370}371return;372}373// else fall through374}375376// Eliminate trailing zeros.377while (count > 1 && digits[count - 1] == '0') {378--count;379}380381// Eliminate digits beyond maximum digits to be displayed.382// Round up if appropriate.383round(fixedPoint ? (maximumDigits + decimalAt) : maximumDigits,384roundedUp, valueExactAsDecimal);385386}387388/**389* Round the representation to the given number of digits.390* @param maximumDigits The maximum number of digits to be shown.391* @param alreadyRounded whether or not rounding up has already happened.392* @param valueExactAsDecimal whether or not collected digits provide393* an exact decimal representation of the value.394*395* Upon return, count will be less than or equal to maximumDigits.396*/397private final void round(int maximumDigits,398boolean alreadyRounded,399boolean valueExactAsDecimal) {400// Eliminate digits beyond maximum digits to be displayed.401// Round up if appropriate.402if (maximumDigits >= 0 && maximumDigits < count) {403if (shouldRoundUp(maximumDigits, alreadyRounded, valueExactAsDecimal)) {404// Rounding up involved incrementing digits from LSD to MSD.405// In most cases this is simple, but in a worst case situation406// (9999..99) we have to adjust the decimalAt value.407for (;;) {408--maximumDigits;409if (maximumDigits < 0) {410// We have all 9's, so we increment to a single digit411// of one and adjust the exponent.412digits[0] = '1';413++decimalAt;414maximumDigits = 0; // Adjust the count415break;416}417418++digits[maximumDigits];419if (digits[maximumDigits] <= '9') break;420// digits[maximumDigits] = '0'; // Unnecessary since we'll truncate this421}422++maximumDigits; // Increment for use as count423}424count = maximumDigits;425426// Eliminate trailing zeros.427while (count > 1 && digits[count-1] == '0') {428--count;429}430}431}432433434/**435* Return true if truncating the representation to the given number436* of digits will result in an increment to the last digit. This437* method implements the rounding modes defined in the438* java.math.RoundingMode class.439* [bnf]440* @param maximumDigits the number of digits to keep, from 0 to441* {@code count-1}. If 0, then all digits are rounded away, and442* this method returns true if a one should be generated (e.g., formatting443* 0.09 with "#.#").444* @param alreadyRounded whether or not rounding up has already happened.445* @param valueExactAsDecimal whether or not collected digits provide446* an exact decimal representation of the value.447* @throws ArithmeticException if rounding is needed with rounding448* mode being set to RoundingMode.UNNECESSARY449* @return true if digit {@code maximumDigits-1} should be450* incremented451*/452private boolean shouldRoundUp(int maximumDigits,453boolean alreadyRounded,454boolean valueExactAsDecimal) {455if (maximumDigits < count) {456/*457* To avoid erroneous double-rounding or truncation when converting458* a binary double value to text, information about the exactness459* of the conversion result in FloatingDecimal, as well as any460* rounding done, is needed in this class.461*462* - For the HALF_DOWN, HALF_EVEN, HALF_UP rounding rules below:463* In the case of formating float or double, We must take into464* account what FloatingDecimal has done in the binary to decimal465* conversion.466*467* Considering the tie cases, FloatingDecimal may round up the468* value (returning decimal digits equal to tie when it is below),469* or "truncate" the value to the tie while value is above it,470* or provide the exact decimal digits when the binary value can be471* converted exactly to its decimal representation given formating472* rules of FloatingDecimal ( we have thus an exact decimal473* representation of the binary value).474*475* - If the double binary value was converted exactly as a decimal476* value, then DigitList code must apply the expected rounding477* rule.478*479* - If FloatingDecimal already rounded up the decimal value,480* DigitList should neither round up the value again in any of481* the three rounding modes above.482*483* - If FloatingDecimal has truncated the decimal value to484* an ending '5' digit, DigitList should round up the value in485* all of the three rounding modes above.486*487*488* This has to be considered only if digit at maximumDigits index489* is exactly the last one in the set of digits, otherwise there are490* remaining digits after that position and we don't have to consider491* what FloatingDecimal did.492*493* - Other rounding modes are not impacted by these tie cases.494*495* - For other numbers that are always converted to exact digits496* (like BigInteger, Long, ...), the passed alreadyRounded boolean497* have to be set to false, and valueExactAsDecimal has to be set to498* true in the upper DigitList call stack, providing the right state499* for those situations..500*/501502switch(roundingMode) {503case UP:504for (int i=maximumDigits; i<count; ++i) {505if (digits[i] != '0') {506return true;507}508}509break;510case DOWN:511break;512case CEILING:513for (int i=maximumDigits; i<count; ++i) {514if (digits[i] != '0') {515return !isNegative;516}517}518break;519case FLOOR:520for (int i=maximumDigits; i<count; ++i) {521if (digits[i] != '0') {522return isNegative;523}524}525break;526case HALF_UP:527case HALF_DOWN:528if (digits[maximumDigits] > '5') {529// Value is above tie ==> must round up530return true;531} else if (digits[maximumDigits] == '5') {532// Digit at rounding position is a '5'. Tie cases.533if (maximumDigits != (count - 1)) {534// There are remaining digits. Above tie => must round up535return true;536} else {537// Digit at rounding position is the last one !538if (valueExactAsDecimal) {539// Exact binary representation. On the tie.540// Apply rounding given by roundingMode.541return roundingMode == RoundingMode.HALF_UP;542} else {543// Not an exact binary representation.544// Digit sequence either rounded up or truncated.545// Round up only if it was truncated.546return !alreadyRounded;547}548}549}550// Digit at rounding position is < '5' ==> no round up.551// Just let do the default, which is no round up (thus break).552break;553case HALF_EVEN:554// Implement IEEE half-even rounding555if (digits[maximumDigits] > '5') {556return true;557} else if (digits[maximumDigits] == '5' ) {558if (maximumDigits == (count - 1)) {559// the rounding position is exactly the last index :560if (alreadyRounded)561// If FloatingDecimal rounded up (value was below tie),562// then we should not round up again.563return false;564565if (!valueExactAsDecimal)566// Otherwise if the digits don't represent exact value,567// value was above tie and FloatingDecimal truncated568// digits to tie. We must round up.569return true;570else {571// This is an exact tie value, and FloatingDecimal572// provided all of the exact digits. We thus apply573// HALF_EVEN rounding rule.574return ((maximumDigits > 0) &&575(digits[maximumDigits-1] % 2 != 0));576}577} else {578// Rounds up if it gives a non null digit after '5'579for (int i=maximumDigits+1; i<count; ++i) {580if (digits[i] != '0')581return true;582}583}584}585break;586case UNNECESSARY:587for (int i=maximumDigits; i<count; ++i) {588if (digits[i] != '0') {589throw new ArithmeticException(590"Rounding needed with the rounding mode being set to RoundingMode.UNNECESSARY");591}592}593break;594default:595assert false;596}597}598return false;599}600601/**602* Utility routine to set the value of the digit list from a long603*/604final void set(boolean isNegative, long source) {605set(isNegative, source, 0);606}607608/**609* Set the digit list to a representation of the given long value.610* @param isNegative Boolean value indicating whether the number is negative.611* @param source Value to be converted; must be >= 0 or ==612* Long.MIN_VALUE.613* @param maximumDigits The most digits which should be converted.614* If maximumDigits is lower than the number of significant digits615* in source, the representation will be rounded. Ignored if <= 0.616*/617final void set(boolean isNegative, long source, int maximumDigits) {618this.isNegative = isNegative;619620// This method does not expect a negative number. However,621// "source" can be a Long.MIN_VALUE (-9223372036854775808),622// if the number being formatted is a Long.MIN_VALUE. In that623// case, it will be formatted as -Long.MIN_VALUE, a number624// which is outside the legal range of a long, but which can625// be represented by DigitList.626if (source <= 0) {627if (source == Long.MIN_VALUE) {628decimalAt = count = MAX_COUNT;629System.arraycopy(LONG_MIN_REP, 0, digits, 0, count);630} else {631decimalAt = count = 0; // Values <= 0 format as zero632}633} else {634// Rewritten to improve performance. I used to call635// Long.toString(), which was about 4x slower than this code.636int left = MAX_COUNT;637int right;638while (source > 0) {639digits[--left] = (char)('0' + (source % 10));640source /= 10;641}642decimalAt = MAX_COUNT - left;643// Don't copy trailing zeros. We are guaranteed that there is at644// least one non-zero digit, so we don't have to check lower bounds.645for (right = MAX_COUNT - 1; digits[right] == '0'; --right)646;647count = right - left + 1;648System.arraycopy(digits, left, digits, 0, count);649}650if (maximumDigits > 0) round(maximumDigits, false, true);651}652653/**654* Set the digit list to a representation of the given BigDecimal value.655* This method supports both fixed-point and exponential notation.656* @param isNegative Boolean value indicating whether the number is negative.657* @param source Value to be converted; must not be a value <= 0.658* @param maximumDigits The most fractional or total digits which should659* be converted.660* @param fixedPoint If true, then maximumDigits is the maximum661* fractional digits to be converted. If false, total digits.662*/663final void set(boolean isNegative, BigDecimal source, int maximumDigits, boolean fixedPoint) {664String s = source.toString();665extendDigits(s.length());666667set(isNegative, s,668false, true,669maximumDigits, fixedPoint);670}671672/**673* Set the digit list to a representation of the given BigInteger value.674* @param isNegative Boolean value indicating whether the number is negative.675* @param source Value to be converted; must be >= 0.676* @param maximumDigits The most digits which should be converted.677* If maximumDigits is lower than the number of significant digits678* in source, the representation will be rounded. Ignored if <= 0.679*/680final void set(boolean isNegative, BigInteger source, int maximumDigits) {681this.isNegative = isNegative;682String s = source.toString();683int len = s.length();684extendDigits(len);685s.getChars(0, len, digits, 0);686687decimalAt = len;688int right;689for (right = len - 1; right >= 0 && digits[right] == '0'; --right)690;691count = right + 1;692693if (maximumDigits > 0) {694round(maximumDigits, false, true);695}696}697698/**699* equality test between two digit lists.700*/701public boolean equals(Object obj) {702if (this == obj) // quick check703return true;704if (!(obj instanceof DigitList other)) // (1) same object?705return false;706if (count != other.count ||707decimalAt != other.decimalAt)708return false;709for (int i = 0; i < count; i++)710if (digits[i] != other.digits[i])711return false;712return true;713}714715/**716* Generates the hash code for the digit list.717*/718public int hashCode() {719int hashcode = decimalAt;720721for (int i = 0; i < count; i++) {722hashcode = hashcode * 37 + digits[i];723}724725return hashcode;726}727728/**729* Creates a copy of this object.730* @return a clone of this instance.731*/732public Object clone() {733try {734DigitList other = (DigitList) super.clone();735char[] newDigits = new char[digits.length];736System.arraycopy(digits, 0, newDigits, 0, digits.length);737other.digits = newDigits;738other.tempBuffer = null;739return other;740} catch (CloneNotSupportedException e) {741throw new InternalError(e);742}743}744745/**746* Returns true if this DigitList represents Long.MIN_VALUE;747* false, otherwise. This is required so that getLong() works.748*/749private boolean isLongMIN_VALUE() {750if (decimalAt != count || count != MAX_COUNT) {751return false;752}753754for (int i = 0; i < count; ++i) {755if (digits[i] != LONG_MIN_REP[i]) return false;756}757758return true;759}760761private static final int parseInt(char[] str, int offset, int strLen) {762char c;763boolean positive = true;764if ((c = str[offset]) == '-') {765positive = false;766offset++;767} else if (c == '+') {768offset++;769}770771int value = 0;772while (offset < strLen) {773c = str[offset++];774if (c >= '0' && c <= '9') {775value = value * 10 + (c - '0');776} else {777break;778}779}780return positive ? value : -value;781}782783// The digit part of -9223372036854775808L784private static final char[] LONG_MIN_REP = "9223372036854775808".toCharArray();785786public String toString() {787if (isZero()) {788return "0";789}790StringBuffer buf = getStringBuffer();791buf.append("0.");792buf.append(digits, 0, count);793buf.append("x10^");794buf.append(decimalAt);795return buf.toString();796}797798private StringBuffer tempBuffer;799800private StringBuffer getStringBuffer() {801if (tempBuffer == null) {802tempBuffer = new StringBuffer(MAX_COUNT);803} else {804tempBuffer.setLength(0);805}806return tempBuffer;807}808809private void extendDigits(int len) {810if (len > digits.length) {811digits = new char[len];812}813}814815private final char[] getDataChars(int length) {816if (data == null || data.length < length) {817data = new char[length];818}819return data;820}821}822823824