1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 
28 #ifndef DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_
29 #define DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_
30 
31 #include "mozilla/Types.h"
32 #include "utils.h"
33 
34 namespace double_conversion {
35 
36 class DoubleToStringConverter {
37  public:
38   // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
39   // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
40   // function returns false.
41   static const int kMaxFixedDigitsBeforePoint = 60;
42   static const int kMaxFixedDigitsAfterPoint = 60;
43 
44   // When calling ToExponential with a requested_digits
45   // parameter > kMaxExponentialDigits then the function returns false.
46   static const int kMaxExponentialDigits = 120;
47 
48   // When calling ToPrecision with a requested_digits
49   // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
50   // then the function returns false.
51   static const int kMinPrecisionDigits = 1;
52   static const int kMaxPrecisionDigits = 120;
53 
54   enum Flags {
55     NO_FLAGS = 0,
56     EMIT_POSITIVE_EXPONENT_SIGN = 1,
57     EMIT_TRAILING_DECIMAL_POINT = 2,
58     EMIT_TRAILING_ZERO_AFTER_POINT = 4,
59     UNIQUE_ZERO = 8
60   };
61 
62   // Flags should be a bit-or combination of the possible Flags-enum.
63   //  - NO_FLAGS: no special flags.
64   //  - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
65   //    form, emits a '+' for positive exponents. Example: 1.2e+2.
66   //  - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
67   //    converted into decimal format then a trailing decimal point is appended.
68   //    Example: 2345.0 is converted to "2345.".
69   //  - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
70   //    emits a trailing '0'-character. This flag requires the
71   //    EXMIT_TRAILING_DECIMAL_POINT flag.
72   //    Example: 2345.0 is converted to "2345.0".
73   //  - UNIQUE_ZERO: "-0.0" is converted to "0.0".
74   //
75   // Infinity symbol and nan_symbol provide the string representation for these
76   // special values. If the string is NULL and the special value is encountered
77   // then the conversion functions return false.
78   //
79   // The exponent_character is used in exponential representations. It is
80   // usually 'e' or 'E'.
81   //
82   // When converting to the shortest representation the converter will
83   // represent input numbers in decimal format if they are in the interval
84   // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
85   //    (lower boundary included, greater boundary excluded).
86   // Example: with decimal_in_shortest_low = -6 and
87   //               decimal_in_shortest_high = 21:
88   //   ToShortest(0.000001)  -> "0.000001"
89   //   ToShortest(0.0000001) -> "1e-7"
90   //   ToShortest(111111111111111111111.0)  -> "111111111111111110000"
91   //   ToShortest(100000000000000000000.0)  -> "100000000000000000000"
92   //   ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
93   //
94   // When converting to precision mode the converter may add
95   // max_leading_padding_zeroes before returning the number in exponential
96   // format.
97   // Example with max_leading_padding_zeroes_in_precision_mode = 6.
98   //   ToPrecision(0.0000012345, 2) -> "0.0000012"
99   //   ToPrecision(0.00000012345, 2) -> "1.2e-7"
100   // Similarily the converter may add up to
101   // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
102   // returning an exponential representation. A zero added by the
103   // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
104   // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
105   //   ToPrecision(230.0, 2) -> "230"
106   //   ToPrecision(230.0, 2) -> "230."  with EMIT_TRAILING_DECIMAL_POINT.
107   //   ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
108   //
109   // The min_exponent_width is used for exponential representations.
110   // The converter adds leading '0's to the exponent until the exponent
111   // is at least min_exponent_width digits long.
112   // The min_exponent_width is clamped to 5.
113   // As such, the exponent may never have more than 5 digits in total.
114   DoubleToStringConverter(int flags,
115                           const char* infinity_symbol,
116                           const char* nan_symbol,
117                           char exponent_character,
118                           int decimal_in_shortest_low,
119                           int decimal_in_shortest_high,
120                           int max_leading_padding_zeroes_in_precision_mode,
121                           int max_trailing_padding_zeroes_in_precision_mode,
122                           int min_exponent_width = 0)
flags_(flags)123       : flags_(flags),
124         infinity_symbol_(infinity_symbol),
125         nan_symbol_(nan_symbol),
126         exponent_character_(exponent_character),
127         decimal_in_shortest_low_(decimal_in_shortest_low),
128         decimal_in_shortest_high_(decimal_in_shortest_high),
129         max_leading_padding_zeroes_in_precision_mode_(
130             max_leading_padding_zeroes_in_precision_mode),
131         max_trailing_padding_zeroes_in_precision_mode_(
132             max_trailing_padding_zeroes_in_precision_mode),
133         min_exponent_width_(min_exponent_width) {
134     // When 'trailing zero after the point' is set, then 'trailing point'
135     // must be set too.
136     DOUBLE_CONVERSION_ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
137         !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
138   }
139 
140   // Returns a converter following the EcmaScript specification.
141   static MFBT_API const DoubleToStringConverter& EcmaScriptConverter();
142 
143   // Computes the shortest string of digits that correctly represent the input
144   // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
145   // (see constructor) it then either returns a decimal representation, or an
146   // exponential representation.
147   // Example with decimal_in_shortest_low = -6,
148   //              decimal_in_shortest_high = 21,
149   //              EMIT_POSITIVE_EXPONENT_SIGN activated, and
150   //              EMIT_TRAILING_DECIMAL_POINT deactived:
151   //   ToShortest(0.000001)  -> "0.000001"
152   //   ToShortest(0.0000001) -> "1e-7"
153   //   ToShortest(111111111111111111111.0)  -> "111111111111111110000"
154   //   ToShortest(100000000000000000000.0)  -> "100000000000000000000"
155   //   ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
156   //
157   // Note: the conversion may round the output if the returned string
158   // is accurate enough to uniquely identify the input-number.
159   // For example the most precise representation of the double 9e59 equals
160   // "899999999999999918767229449717619953810131273674690656206848", but
161   // the converter will return the shorter (but still correct) "9e59".
162   //
163   // Returns true if the conversion succeeds. The conversion always succeeds
164   // except when the input value is special and no infinity_symbol or
165   // nan_symbol has been given to the constructor.
ToShortest(double value,StringBuilder * result_builder)166   bool ToShortest(double value, StringBuilder* result_builder) const {
167     return ToShortestIeeeNumber(value, result_builder, SHORTEST);
168   }
169 
170   // Same as ToShortest, but for single-precision floats.
ToShortestSingle(float value,StringBuilder * result_builder)171   bool ToShortestSingle(float value, StringBuilder* result_builder) const {
172     return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE);
173   }
174 
175 
176   // Computes a decimal representation with a fixed number of digits after the
177   // decimal point. The last emitted digit is rounded.
178   //
179   // Examples:
180   //   ToFixed(3.12, 1) -> "3.1"
181   //   ToFixed(3.1415, 3) -> "3.142"
182   //   ToFixed(1234.56789, 4) -> "1234.5679"
183   //   ToFixed(1.23, 5) -> "1.23000"
184   //   ToFixed(0.1, 4) -> "0.1000"
185   //   ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
186   //   ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
187   //   ToFixed(0.1, 17) -> "0.10000000000000001"
188   //
189   // If requested_digits equals 0, then the tail of the result depends on
190   // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
191   // Examples, for requested_digits == 0,
192   //   let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
193   //    - false and false: then 123.45 -> 123
194   //                             0.678 -> 1
195   //    - true and false: then 123.45 -> 123.
196   //                            0.678 -> 1.
197   //    - true and true: then 123.45 -> 123.0
198   //                           0.678 -> 1.0
199   //
200   // Returns true if the conversion succeeds. The conversion always succeeds
201   // except for the following cases:
202   //   - the input value is special and no infinity_symbol or nan_symbol has
203   //     been provided to the constructor,
204   //   - 'value' > 10^kMaxFixedDigitsBeforePoint, or
205   //   - 'requested_digits' > kMaxFixedDigitsAfterPoint.
206   // The last two conditions imply that the result will never contain more than
207   // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
208   // (one additional character for the sign, and one for the decimal point).
209   MFBT_API bool ToFixed(double value,
210                int requested_digits,
211                StringBuilder* result_builder) const;
212 
213   // Computes a representation in exponential format with requested_digits
214   // after the decimal point. The last emitted digit is rounded.
215   // If requested_digits equals -1, then the shortest exponential representation
216   // is computed.
217   //
218   // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
219   //               exponent_character set to 'e'.
220   //   ToExponential(3.12, 1) -> "3.1e0"
221   //   ToExponential(5.0, 3) -> "5.000e0"
222   //   ToExponential(0.001, 2) -> "1.00e-3"
223   //   ToExponential(3.1415, -1) -> "3.1415e0"
224   //   ToExponential(3.1415, 4) -> "3.1415e0"
225   //   ToExponential(3.1415, 3) -> "3.142e0"
226   //   ToExponential(123456789000000, 3) -> "1.235e14"
227   //   ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
228   //   ToExponential(1000000000000000019884624838656.0, 32) ->
229   //                     "1.00000000000000001988462483865600e30"
230   //   ToExponential(1234, 0) -> "1e3"
231   //
232   // Returns true if the conversion succeeds. The conversion always succeeds
233   // except for the following cases:
234   //   - the input value is special and no infinity_symbol or nan_symbol has
235   //     been provided to the constructor,
236   //   - 'requested_digits' > kMaxExponentialDigits.
237   // The last condition implies that the result will never contain more than
238   // kMaxExponentialDigits + 8 characters (the sign, the digit before the
239   // decimal point, the decimal point, the exponent character, the
240   // exponent's sign, and at most 3 exponent digits).
241   MFBT_API bool ToExponential(double value,
242                      int requested_digits,
243                      StringBuilder* result_builder) const;
244 
245   // Computes 'precision' leading digits of the given 'value' and returns them
246   // either in exponential or decimal format, depending on
247   // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
248   // constructor).
249   // The last computed digit is rounded.
250   //
251   // Example with max_leading_padding_zeroes_in_precision_mode = 6.
252   //   ToPrecision(0.0000012345, 2) -> "0.0000012"
253   //   ToPrecision(0.00000012345, 2) -> "1.2e-7"
254   // Similarily the converter may add up to
255   // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
256   // returning an exponential representation. A zero added by the
257   // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
258   // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
259   //   ToPrecision(230.0, 2) -> "230"
260   //   ToPrecision(230.0, 2) -> "230."  with EMIT_TRAILING_DECIMAL_POINT.
261   //   ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
262   // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
263   //    EMIT_TRAILING_ZERO_AFTER_POINT:
264   //   ToPrecision(123450.0, 6) -> "123450"
265   //   ToPrecision(123450.0, 5) -> "123450"
266   //   ToPrecision(123450.0, 4) -> "123500"
267   //   ToPrecision(123450.0, 3) -> "123000"
268   //   ToPrecision(123450.0, 2) -> "1.2e5"
269   //
270   // Returns true if the conversion succeeds. The conversion always succeeds
271   // except for the following cases:
272   //   - the input value is special and no infinity_symbol or nan_symbol has
273   //     been provided to the constructor,
274   //   - precision < kMinPericisionDigits
275   //   - precision > kMaxPrecisionDigits
276   // The last condition implies that the result will never contain more than
277   // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
278   // exponent character, the exponent's sign, and at most 3 exponent digits).
279   MFBT_API bool ToPrecision(double value,
280                    int precision,
281                    bool* used_exponential_notation,
282                    StringBuilder* result_builder) const;
283 
284   enum DtoaMode {
285     // Produce the shortest correct representation.
286     // For example the output of 0.299999999999999988897 is (the less accurate
287     // but correct) 0.3.
288     SHORTEST,
289     // Same as SHORTEST, but for single-precision floats.
290     SHORTEST_SINGLE,
291     // Produce a fixed number of digits after the decimal point.
292     // For instance fixed(0.1, 4) becomes 0.1000
293     // If the input number is big, the output will be big.
294     FIXED,
295     // Fixed number of digits (independent of the decimal point).
296     PRECISION
297   };
298 
299   // The maximal number of digits that are needed to emit a double in base 10.
300   // A higher precision can be achieved by using more digits, but the shortest
301   // accurate representation of any double will never use more digits than
302   // kBase10MaximalLength.
303   // Note that DoubleToAscii null-terminates its input. So the given buffer
304   // should be at least kBase10MaximalLength + 1 characters long.
305   static const MFBT_DATA int kBase10MaximalLength = 17;
306 
307   // Converts the given double 'v' to digit characters. 'v' must not be NaN,
308   // +Infinity, or -Infinity. In SHORTEST_SINGLE-mode this restriction also
309   // applies to 'v' after it has been casted to a single-precision float. That
310   // is, in this mode static_cast<float>(v) must not be NaN, +Infinity or
311   // -Infinity.
312   //
313   // The result should be interpreted as buffer * 10^(point-length).
314   //
315   // The digits are written to the buffer in the platform's charset, which is
316   // often UTF-8 (with ASCII-range digits) but may be another charset, such
317   // as EBCDIC.
318   //
319   // The output depends on the given mode:
320   //  - SHORTEST: produce the least amount of digits for which the internal
321   //   identity requirement is still satisfied. If the digits are printed
322   //   (together with the correct exponent) then reading this number will give
323   //   'v' again. The buffer will choose the representation that is closest to
324   //   'v'. If there are two at the same distance, than the one farther away
325   //   from 0 is chosen (halfway cases - ending with 5 - are rounded up).
326   //   In this mode the 'requested_digits' parameter is ignored.
327   //  - SHORTEST_SINGLE: same as SHORTEST but with single-precision.
328   //  - FIXED: produces digits necessary to print a given number with
329   //   'requested_digits' digits after the decimal point. The produced digits
330   //   might be too short in which case the caller has to fill the remainder
331   //   with '0's.
332   //   Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
333   //   Halfway cases are rounded towards +/-Infinity (away from 0). The call
334   //   toFixed(0.15, 2) thus returns buffer="2", point=0.
335   //   The returned buffer may contain digits that would be truncated from the
336   //   shortest representation of the input.
337   //  - PRECISION: produces 'requested_digits' where the first digit is not '0'.
338   //   Even though the length of produced digits usually equals
339   //   'requested_digits', the function is allowed to return fewer digits, in
340   //   which case the caller has to fill the missing digits with '0's.
341   //   Halfway cases are again rounded away from 0.
342   // DoubleToAscii expects the given buffer to be big enough to hold all
343   // digits and a terminating null-character. In SHORTEST-mode it expects a
344   // buffer of at least kBase10MaximalLength + 1. In all other modes the
345   // requested_digits parameter and the padding-zeroes limit the size of the
346   // output. Don't forget the decimal point, the exponent character and the
347   // terminating null-character when computing the maximal output size.
348   // The given length is only used in debug mode to ensure the buffer is big
349   // enough.
350   static MFBT_API void DoubleToAscii(double v,
351                             DtoaMode mode,
352                             int requested_digits,
353                             char* buffer,
354                             int buffer_length,
355                             bool* sign,
356                             int* length,
357                             int* point);
358 
359  private:
360   // Implementation for ToShortest and ToShortestSingle.
361   MFBT_API bool ToShortestIeeeNumber(double value,
362                             StringBuilder* result_builder,
363                             DtoaMode mode) const;
364 
365   // If the value is a special value (NaN or Infinity) constructs the
366   // corresponding string using the configured infinity/nan-symbol.
367   // If either of them is NULL or the value is not special then the
368   // function returns false.
369   MFBT_API bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
370   // Constructs an exponential representation (i.e. 1.234e56).
371   // The given exponent assumes a decimal point after the first decimal digit.
372   MFBT_API void CreateExponentialRepresentation(const char* decimal_digits,
373                                        int length,
374                                        int exponent,
375                                        StringBuilder* result_builder) const;
376   // Creates a decimal representation (i.e 1234.5678).
377   MFBT_API void CreateDecimalRepresentation(const char* decimal_digits,
378                                    int length,
379                                    int decimal_point,
380                                    int digits_after_point,
381                                    StringBuilder* result_builder) const;
382 
383   const int flags_;
384   const char* const infinity_symbol_;
385   const char* const nan_symbol_;
386   const char exponent_character_;
387   const int decimal_in_shortest_low_;
388   const int decimal_in_shortest_high_;
389   const int max_leading_padding_zeroes_in_precision_mode_;
390   const int max_trailing_padding_zeroes_in_precision_mode_;
391   const int min_exponent_width_;
392 
393   DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
394 };
395 
396 }  // namespace double_conversion
397 
398 #endif  // DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_
399