1 // © 2017 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 #include "unicode/utypes.h"
6 #if !UCONFIG_NO_FORMATTING
7 #ifndef __NUMBER_DECIMALQUANTITY_H__
8 #define __NUMBER_DECIMALQUANTITY_H__
11 #include "unicode/umachine.h"
12 #include "standardplural.h"
13 #include "plurrule_impl.h"
14 #include "number_types.h"
16 U_NAMESPACE_BEGIN
namespace number
{
19 // Forward-declare (maybe don't want number_utils.h included here):
23 * An class for representing a number to be processed by the decimal formatting pipeline. Includes
24 * methods for rounding, plural rules, and decimal digit extraction.
26 * <p>By design, this is NOT IMMUTABLE and NOT THREAD SAFE. It is intended to be an intermediate
27 * object holding state during a pass through the decimal formatting pipeline.
29 * <p>Represents numbers and digit display properties using Binary Coded Decimal (BCD).
31 * <p>Java has multiple implementations for testing, but C++ has only one implementation.
33 class U_I18N_API DecimalQuantity
: public IFixedDecimal
, public UMemory
{
35 /** Copy constructor. */
36 DecimalQuantity(const DecimalQuantity
&other
);
38 /** Move constructor. */
39 DecimalQuantity(DecimalQuantity
&&src
) U_NOEXCEPT
;
43 ~DecimalQuantity() override
;
46 * Sets this instance to be equal to another instance.
48 * @param other The instance to copy from.
50 DecimalQuantity
&operator=(const DecimalQuantity
&other
);
52 /** Move assignment */
53 DecimalQuantity
&operator=(DecimalQuantity
&& src
) U_NOEXCEPT
;
56 * Sets the minimum integer digits that this {@link DecimalQuantity} should generate.
57 * This method does not perform rounding.
59 * @param minInt The minimum number of integer digits.
61 void setMinInteger(int32_t minInt
);
64 * Sets the minimum fraction digits that this {@link DecimalQuantity} should generate.
65 * This method does not perform rounding.
67 * @param minFrac The minimum number of fraction digits.
69 void setMinFraction(int32_t minFrac
);
72 * Truncates digits from the upper magnitude of the number in order to satisfy the
73 * specified maximum number of integer digits.
75 * @param maxInt The maximum number of integer digits.
77 void applyMaxInteger(int32_t maxInt
);
80 * Rounds the number to a specified interval, such as 0.05.
82 * <p>If rounding to a power of ten, use the more efficient {@link #roundToMagnitude} instead.
84 * @param roundingIncrement The increment to which to round.
85 * @param roundingMode The {@link RoundingMode} to use if rounding is necessary.
87 void roundToIncrement(double roundingIncrement
, RoundingMode roundingMode
,
90 /** Removes all fraction digits. */
94 * Rounds the number to the nearest multiple of 5 at the specified magnitude.
95 * For example, when magnitude == -2, this performs rounding to the nearest 0.05.
97 * @param magnitude The magnitude at which the digit should become either 0 or 5.
98 * @param roundingMode Rounding strategy.
100 void roundToNickel(int32_t magnitude
, RoundingMode roundingMode
, UErrorCode
& status
);
103 * Rounds the number to a specified magnitude (power of ten).
105 * @param roundingMagnitude The power of ten to which to round. For example, a value of -2 will
106 * round to 2 decimal places.
107 * @param roundingMode The {@link RoundingMode} to use if rounding is necessary.
109 void roundToMagnitude(int32_t magnitude
, RoundingMode roundingMode
, UErrorCode
& status
);
112 * Rounds the number to an infinite number of decimal points. This has no effect except for
113 * forcing the double in {@link DecimalQuantity_AbstractBCD} to adopt its exact representation.
115 void roundToInfinity();
118 * Multiply the internal value. Uses decNumber.
120 * @param multiplicand The value by which to multiply.
122 void multiplyBy(const DecNum
& multiplicand
, UErrorCode
& status
);
125 * Divide the internal value. Uses decNumber.
127 * @param multiplicand The value by which to multiply.
129 void divideBy(const DecNum
& divisor
, UErrorCode
& status
);
131 /** Flips the sign from positive to negative and back. */
135 * Scales the number by a power of ten. For example, if the value is currently "1234.56", calling
136 * this method with delta=-3 will change the value to "1.23456".
138 * @param delta The number of magnitudes of ten to change by.
139 * @return true if integer overflow occured; false otherwise.
141 bool adjustMagnitude(int32_t delta
);
144 * @return The power of ten corresponding to the most significant nonzero digit.
145 * The number must not be zero.
147 int32_t getMagnitude() const;
149 /** @return Whether the value represented by this {@link DecimalQuantity} is zero. */
152 /** @return Whether the value represented by this {@link DecimalQuantity} is less than zero. */
153 bool isNegative() const;
155 /** @return -1 if the value is negative; 1 if positive; or 0 if zero. */
156 int8_t signum() const;
158 /** @return Whether the value represented by this {@link DecimalQuantity} is infinite. */
159 bool isInfinite() const U_OVERRIDE
;
161 /** @return Whether the value represented by this {@link DecimalQuantity} is not a number. */
162 bool isNaN() const U_OVERRIDE
;
164 /** @param truncateIfOverflow if false and the number does NOT fit, fails with an assertion error. */
165 int64_t toLong(bool truncateIfOverflow
= false) const;
167 uint64_t toFractionLong(bool includeTrailingZeros
) const;
170 * Returns whether or not a Long can fully represent the value stored in this DecimalQuantity.
171 * @param ignoreFraction if true, silently ignore digits after the decimal place.
173 bool fitsInLong(bool ignoreFraction
= false) const;
175 /** @return The value contained in this {@link DecimalQuantity} approximated as a double. */
176 double toDouble() const;
178 /** Computes a DecNum representation of this DecimalQuantity, saving it to the output parameter. */
179 void toDecNum(DecNum
& output
, UErrorCode
& status
) const;
181 DecimalQuantity
&setToInt(int32_t n
);
183 DecimalQuantity
&setToLong(int64_t n
);
185 DecimalQuantity
&setToDouble(double n
);
187 /** decNumber is similar to BigDecimal in Java. */
188 DecimalQuantity
&setToDecNumber(StringPiece n
, UErrorCode
& status
);
190 /** Internal method if the caller already has a DecNum. */
191 DecimalQuantity
&setToDecNum(const DecNum
& n
, UErrorCode
& status
);
194 * Appends a digit, optionally with one or more leading zeros, to the end of the value represented
195 * by this DecimalQuantity.
197 * <p>The primary use of this method is to construct numbers during a parsing loop. It allows
198 * parsing to take advantage of the digit list infrastructure primarily designed for formatting.
200 * @param value The digit to append.
201 * @param leadingZeros The number of zeros to append before the digit. For example, if the value
202 * in this instance starts as 12.3, and you append a 4 with 1 leading zero, the value becomes
204 * @param appendAsInteger If true, increase the magnitude of existing digits to make room for the
205 * new digit. If false, append to the end like a fraction digit. If true, there must not be
206 * any fraction digits already in the number.
208 * @deprecated This API is ICU internal only.
210 void appendDigit(int8_t value
, int32_t leadingZeros
, bool appendAsInteger
);
212 double getPluralOperand(PluralOperand operand
) const U_OVERRIDE
;
214 bool hasIntegerValue() const U_OVERRIDE
;
217 * Gets the digit at the specified magnitude. For example, if the represented number is 12.3,
218 * getDigit(-1) returns 3, since 3 is the digit corresponding to 10^-1.
220 * @param magnitude The magnitude of the digit.
221 * @return The digit at the specified magnitude.
223 int8_t getDigit(int32_t magnitude
) const;
226 * Gets the largest power of ten that needs to be displayed. The value returned by this function
227 * will be bounded between minInt and maxInt.
229 * @return The highest-magnitude digit to be displayed.
231 int32_t getUpperDisplayMagnitude() const;
234 * Gets the smallest power of ten that needs to be displayed. The value returned by this function
235 * will be bounded between -minFrac and -maxFrac.
237 * @return The lowest-magnitude digit to be displayed.
239 int32_t getLowerDisplayMagnitude() const;
241 int32_t fractionCount() const;
243 int32_t fractionCountWithoutTrailingZeros() const;
247 /** This method is for internal testing only. */
248 uint64_t getPositionFingerprint() const;
251 // * If the given {@link FieldPosition} is a {@link UFieldPosition}, populates it with the fraction
252 // * length and fraction long value. If the argument is not a {@link UFieldPosition}, nothing
255 // * @param fp The {@link UFieldPosition} to populate.
257 // void populateUFieldPosition(FieldPosition fp);
260 * Checks whether the bytes stored in this instance are all valid. For internal unit testing only.
262 * @return An error message if this instance is invalid, or null if this instance is healthy.
264 const char16_t* checkHealth() const;
266 UnicodeString
toString() const;
268 /** Returns the string in standard exponential notation. */
269 UnicodeString
toScientificString() const;
271 /** Returns the string without exponential notation. Slightly slower than toScientificString(). */
272 UnicodeString
toPlainString() const;
274 /** Visible for testing */
275 inline bool isUsingBytes() { return usingBytes
; }
277 /** Visible for testing */
278 inline bool isExplicitExactDouble() { return explicitExactDouble
; }
280 bool operator==(const DecimalQuantity
& other
) const;
282 inline bool operator!=(const DecimalQuantity
& other
) const {
283 return !(*this == other
);
287 * Bogus flag for when a DecimalQuantity is stored on the stack.
293 * The power of ten corresponding to the least significant digit in the BCD. For example, if this
294 * object represents the number "3.14", the BCD will be "0x314" and the scale will be -2.
296 * <p>Note that in {@link java.math.BigDecimal}, the scale is defined differently: the number of
297 * digits after the decimal place, which is the negative of our definition of scale.
302 * The number of digits in the BCD. For example, "1007" has BCD "0x1007" and precision 4. The
303 * maximum precision is 16 since a long can hold only 16 digits.
305 * <p>This value must be re-calculated whenever the value in bcd changes by using {@link
306 * #computePrecisionAndCompact()}.
311 * A bitmask of properties relating to the number represented by this object.
313 * @see #NEGATIVE_FLAG
314 * @see #INFINITY_FLAG
319 // The following three fields relate to the double-to-ascii fast path algorithm.
320 // When a double is given to DecimalQuantityBCD, it is converted to using a fast algorithm. The
321 // fast algorithm guarantees correctness to only the first ~12 digits of the double. The process
322 // of rounding the number ensures that the converted digits are correct, falling back to a slow-
323 // path algorithm if required. Therefore, if a DecimalQuantity is constructed from a double, it
324 // is *required* that roundToMagnitude(), roundToIncrement(), or roundToInfinity() is called. If
325 // you don't round, assertions will fail in certain other methods if you try calling them.
328 * Whether the value in the BCD comes from the double fast path without having been rounded to
334 * The original number provided by the user and which is represented in BCD. Used when we need to
335 * re-compute the BCD for an exact double representation.
340 * The change in magnitude relative to the original double. Used when we need to re-compute the
341 * BCD for an exact double representation.
345 // Positions to keep track of leading and trailing zeros.
346 // lReqPos is the magnitude of the first required leading zero.
347 // rReqPos is the magnitude of the last required trailing zero.
352 * The BCD of the 16 digits of the number represented by this object. Every 4 bits of the long map
353 * to one digit. For example, the number "12345" in BCD is "0x12345".
355 * <p>Whenever bcd changes internally, {@link #compact()} must be called, except in special cases
356 * like setting the digit to zero.
366 bool usingBytes
= false;
369 * Whether this {@link DecimalQuantity} has been explicitly converted to an exact double. true if
370 * backed by a double that was explicitly converted via convertToAccurateDouble; false otherwise.
373 bool explicitExactDouble
= false;
375 void roundToMagnitude(int32_t magnitude
, RoundingMode roundingMode
, bool nickel
, UErrorCode
& status
);
378 * Returns a single digit from the BCD list. No internal state is changed by calling this method.
380 * @param position The position of the digit to pop, counted in BCD units from the least
381 * significant digit. If outside the range supported by the implementation, zero is returned.
382 * @return The digit at the specified location.
384 int8_t getDigitPos(int32_t position
) const;
387 * Sets the digit in the BCD list. This method only sets the digit; it is the caller's
388 * responsibility to call {@link #compact} after setting the digit.
390 * @param position The position of the digit to pop, counted in BCD units from the least
391 * significant digit. If outside the range supported by the implementation, an AssertionError
393 * @param value The digit to set at the specified location.
395 void setDigitPos(int32_t position
, int8_t value
);
398 * Adds zeros to the end of the BCD list. This will result in an invalid BCD representation; it is
399 * the caller's responsibility to do further manipulation and then call {@link #compact}.
401 * @param numDigits The number of zeros to add.
403 void shiftLeft(int32_t numDigits
);
406 * Directly removes digits from the end of the BCD list.
407 * Updates the scale and precision.
409 * CAUTION: it is the caller's responsibility to call {@link #compact} after this method.
411 void shiftRight(int32_t numDigits
);
414 * Directly removes digits from the front of the BCD list.
417 * CAUTION: it is the caller's responsibility to call {@link #compact} after this method.
419 void popFromLeft(int32_t numDigits
);
422 * Sets the internal representation to zero. Clears any values stored in scale, precision,
423 * hasDouble, origDouble, origDelta, and BCD data.
428 * Sets the internal BCD state to represent the value in the given int. The int is guaranteed to
429 * be either positive. The internal state is guaranteed to be empty when this method is called.
431 * @param n The value to consume.
433 void readIntToBcd(int32_t n
);
436 * Sets the internal BCD state to represent the value in the given long. The long is guaranteed to
437 * be either positive. The internal state is guaranteed to be empty when this method is called.
439 * @param n The value to consume.
441 void readLongToBcd(int64_t n
);
443 void readDecNumberToBcd(const DecNum
& dn
);
445 void readDoubleConversionToBcd(const char* buffer
, int32_t length
, int32_t point
);
447 void copyFieldsFrom(const DecimalQuantity
& other
);
449 void copyBcdFrom(const DecimalQuantity
&other
);
451 void moveBcdFrom(DecimalQuantity
& src
);
454 * Removes trailing zeros from the BCD (adjusting the scale as required) and then computes the
455 * precision. The precision is the number of digits in the number up through the greatest nonzero
458 * <p>This method must always be called when bcd changes in order for assumptions to be correct in
459 * methods like {@link #fractionCount()}.
463 void _setToInt(int32_t n
);
465 void _setToLong(int64_t n
);
467 void _setToDoubleFast(double n
);
469 void _setToDecNum(const DecNum
& dn
, UErrorCode
& status
);
471 void convertToAccurateDouble();
473 /** Ensure that a byte array of at least 40 digits is allocated. */
474 void ensureCapacity();
476 void ensureCapacity(int32_t capacity
);
478 /** Switches the internal storage mechanism between the 64-bit long and the byte array. */
479 void switchStorage();
483 } // namespace number
487 #endif //__NUMBER_DECIMALQUANTITY_H__
489 #endif /* #if !UCONFIG_NO_FORMATTING */