double-to-string.h 19 KB

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