Number.Formatting.cs 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Buffers.Text;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Runtime.CompilerServices;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. namespace System
  11. {
  12. // The Format methods provided by the numeric classes convert
  13. // the numeric value to a string using the format string given by the
  14. // format parameter. If the format parameter is null or
  15. // an empty string, the number is formatted as if the string "G" (general
  16. // format) was specified. The info parameter specifies the
  17. // NumberFormatInfo instance to use when formatting the number. If the
  18. // info parameter is null or omitted, the numeric formatting information
  19. // is obtained from the current culture. The NumberFormatInfo supplies
  20. // such information as the characters to use for decimal and thousand
  21. // separators, and the spelling and placement of currency symbols in monetary
  22. // values.
  23. //
  24. // Format strings fall into two categories: Standard format strings and
  25. // user-defined format strings. A format string consisting of a single
  26. // alphabetic character (A-Z or a-z), optionally followed by a sequence of
  27. // digits (0-9), is a standard format string. All other format strings are
  28. // used-defined format strings.
  29. //
  30. // A standard format string takes the form Axx, where A is an
  31. // alphabetic character called the format specifier and xx is a
  32. // sequence of digits called the precision specifier. The format
  33. // specifier controls the type of formatting applied to the number and the
  34. // precision specifier controls the number of significant digits or decimal
  35. // places of the formatting operation. The following table describes the
  36. // supported standard formats.
  37. //
  38. // C c - Currency format. The number is
  39. // converted to a string that represents a currency amount. The conversion is
  40. // controlled by the currency format information of the NumberFormatInfo
  41. // used to format the number. The precision specifier indicates the desired
  42. // number of decimal places. If the precision specifier is omitted, the default
  43. // currency precision given by the NumberFormatInfo is used.
  44. //
  45. // D d - Decimal format. This format is
  46. // supported for integral types only. The number is converted to a string of
  47. // decimal digits, prefixed by a minus sign if the number is negative. The
  48. // precision specifier indicates the minimum number of digits desired in the
  49. // resulting string. If required, the number will be left-padded with zeros to
  50. // produce the number of digits given by the precision specifier.
  51. //
  52. // E e Engineering (scientific) format.
  53. // The number is converted to a string of the form
  54. // "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each
  55. // 'd' indicates a digit (0-9). The string starts with a minus sign if the
  56. // number is negative, and one digit always precedes the decimal point. The
  57. // precision specifier indicates the desired number of digits after the decimal
  58. // point. If the precision specifier is omitted, a default of 6 digits after
  59. // the decimal point is used. The format specifier indicates whether to prefix
  60. // the exponent with an 'E' or an 'e'. The exponent is always consists of a
  61. // plus or minus sign and three digits.
  62. //
  63. // F f Fixed point format. The number is
  64. // converted to a string of the form "-ddd.ddd....", where each
  65. // 'd' indicates a digit (0-9). The string starts with a minus sign if the
  66. // number is negative. The precision specifier indicates the desired number of
  67. // decimal places. If the precision specifier is omitted, the default numeric
  68. // precision given by the NumberFormatInfo is used.
  69. //
  70. // G g - General format. The number is
  71. // converted to the shortest possible decimal representation using fixed point
  72. // or scientific format. The precision specifier determines the number of
  73. // significant digits in the resulting string. If the precision specifier is
  74. // omitted, the number of significant digits is determined by the type of the
  75. // number being converted (10 for int, 19 for long, 7 for
  76. // float, 15 for double, 19 for Currency, and 29 for
  77. // Decimal). Trailing zeros after the decimal point are removed, and the
  78. // resulting string contains a decimal point only if required. The resulting
  79. // string uses fixed point format if the exponent of the number is less than
  80. // the number of significant digits and greater than or equal to -4. Otherwise,
  81. // the resulting string uses scientific format, and the case of the format
  82. // specifier controls whether the exponent is prefixed with an 'E' or an 'e'.
  83. //
  84. // N n Number format. The number is
  85. // converted to a string of the form "-d,ddd,ddd.ddd....", where
  86. // each 'd' indicates a digit (0-9). The string starts with a minus sign if the
  87. // number is negative. Thousand separators are inserted between each group of
  88. // three digits to the left of the decimal point. The precision specifier
  89. // indicates the desired number of decimal places. If the precision specifier
  90. // is omitted, the default numeric precision given by the
  91. // NumberFormatInfo is used.
  92. //
  93. // X x - Hexadecimal format. This format is
  94. // supported for integral types only. The number is converted to a string of
  95. // hexadecimal digits. The format specifier indicates whether to use upper or
  96. // lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF',
  97. // and 'x' for 'abcdef'). The precision specifier indicates the minimum number
  98. // of digits desired in the resulting string. If required, the number will be
  99. // left-padded with zeros to produce the number of digits given by the
  100. // precision specifier.
  101. //
  102. // Some examples of standard format strings and their results are shown in the
  103. // table below. (The examples all assume a default NumberFormatInfo.)
  104. //
  105. // Value Format Result
  106. // 12345.6789 C $12,345.68
  107. // -12345.6789 C ($12,345.68)
  108. // 12345 D 12345
  109. // 12345 D8 00012345
  110. // 12345.6789 E 1.234568E+004
  111. // 12345.6789 E10 1.2345678900E+004
  112. // 12345.6789 e4 1.2346e+004
  113. // 12345.6789 F 12345.68
  114. // 12345.6789 F0 12346
  115. // 12345.6789 F6 12345.678900
  116. // 12345.6789 G 12345.6789
  117. // 12345.6789 G7 12345.68
  118. // 123456789 G7 1.234568E8
  119. // 12345.6789 N 12,345.68
  120. // 123456789 N4 123,456,789.0000
  121. // 0x2c45e x 2c45e
  122. // 0x2c45e X 2C45E
  123. // 0x2c45e X8 0002C45E
  124. //
  125. // Format strings that do not start with an alphabetic character, or that start
  126. // with an alphabetic character followed by a non-digit, are called
  127. // user-defined format strings. The following table describes the formatting
  128. // characters that are supported in user defined format strings.
  129. //
  130. //
  131. // 0 - Digit placeholder. If the value being
  132. // formatted has a digit in the position where the '0' appears in the format
  133. // string, then that digit is copied to the output string. Otherwise, a '0' is
  134. // stored in that position in the output string. The position of the leftmost
  135. // '0' before the decimal point and the rightmost '0' after the decimal point
  136. // determines the range of digits that are always present in the output
  137. // string.
  138. //
  139. // # - Digit placeholder. If the value being
  140. // formatted has a digit in the position where the '#' appears in the format
  141. // string, then that digit is copied to the output string. Otherwise, nothing
  142. // is stored in that position in the output string.
  143. //
  144. // . - Decimal point. The first '.' character
  145. // in the format string determines the location of the decimal separator in the
  146. // formatted value; any additional '.' characters are ignored. The actual
  147. // character used as a the decimal separator in the output string is given by
  148. // the NumberFormatInfo used to format the number.
  149. //
  150. // , - Thousand separator and number scaling.
  151. // The ',' character serves two purposes. First, if the format string contains
  152. // a ',' character between two digit placeholders (0 or #) and to the left of
  153. // the decimal point if one is present, then the output will have thousand
  154. // separators inserted between each group of three digits to the left of the
  155. // decimal separator. The actual character used as a the decimal separator in
  156. // the output string is given by the NumberFormatInfo used to format the
  157. // number. Second, if the format string contains one or more ',' characters
  158. // immediately to the left of the decimal point, or after the last digit
  159. // placeholder if there is no decimal point, then the number will be divided by
  160. // 1000 times the number of ',' characters before it is formatted. For example,
  161. // the format string '0,,' will represent 100 million as just 100. Use of the
  162. // ',' character to indicate scaling does not also cause the formatted number
  163. // to have thousand separators. Thus, to scale a number by 1 million and insert
  164. // thousand separators you would use the format string '#,##0,,'.
  165. //
  166. // % - Percentage placeholder. The presence of
  167. // a '%' character in the format string causes the number to be multiplied by
  168. // 100 before it is formatted. The '%' character itself is inserted in the
  169. // output string where it appears in the format string.
  170. //
  171. // E+ E- e+ e- - Scientific notation.
  172. // If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format
  173. // string and are immediately followed by at least one '0' character, then the
  174. // number is formatted using scientific notation with an 'E' or 'e' inserted
  175. // between the number and the exponent. The number of '0' characters following
  176. // the scientific notation indicator determines the minimum number of digits to
  177. // output for the exponent. The 'E+' and 'e+' formats indicate that a sign
  178. // character (plus or minus) should always precede the exponent. The 'E-' and
  179. // 'e-' formats indicate that a sign character should only precede negative
  180. // exponents.
  181. //
  182. // \ - Literal character. A backslash character
  183. // causes the next character in the format string to be copied to the output
  184. // string as-is. The backslash itself isn't copied, so to place a backslash
  185. // character in the output string, use two backslashes (\\) in the format
  186. // string.
  187. //
  188. // 'ABC' "ABC" - Literal string. Characters
  189. // enclosed in single or double quotation marks are copied to the output string
  190. // as-is and do not affect formatting.
  191. //
  192. // ; - Section separator. The ';' character is
  193. // used to separate sections for positive, negative, and zero numbers in the
  194. // format string.
  195. //
  196. // Other - All other characters are copied to
  197. // the output string in the position they appear.
  198. //
  199. // For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or
  200. // 'e-'), the number is rounded to as many decimal places as there are digit
  201. // placeholders to the right of the decimal point. If the format string does
  202. // not contain a decimal point, the number is rounded to the nearest
  203. // integer. If the number has more digits than there are digit placeholders to
  204. // the left of the decimal point, the extra digits are copied to the output
  205. // string immediately before the first digit placeholder.
  206. //
  207. // For scientific formats, the number is rounded to as many significant digits
  208. // as there are digit placeholders in the format string.
  209. //
  210. // To allow for different formatting of positive, negative, and zero values, a
  211. // user-defined format string may contain up to three sections separated by
  212. // semicolons. The results of having one, two, or three sections in the format
  213. // string are described in the table below.
  214. //
  215. // Sections:
  216. //
  217. // One - The format string applies to all values.
  218. //
  219. // Two - The first section applies to positive values
  220. // and zeros, and the second section applies to negative values. If the number
  221. // to be formatted is negative, but becomes zero after rounding according to
  222. // the format in the second section, then the resulting zero is formatted
  223. // according to the first section.
  224. //
  225. // Three - The first section applies to positive
  226. // values, the second section applies to negative values, and the third section
  227. // applies to zeros. The second section may be left empty (by having no
  228. // characters between the semicolons), in which case the first section applies
  229. // to all non-zero values. If the number to be formatted is non-zero, but
  230. // becomes zero after rounding according to the format in the first or second
  231. // section, then the resulting zero is formatted according to the third
  232. // section.
  233. //
  234. // For both standard and user-defined formatting operations on values of type
  235. // float and double, if the value being formatted is a NaN (Not
  236. // a Number) or a positive or negative infinity, then regardless of the format
  237. // string, the resulting string is given by the NaNSymbol,
  238. // PositiveInfinitySymbol, or NegativeInfinitySymbol property of
  239. // the NumberFormatInfo used to format the number.
  240. internal static partial class Number
  241. {
  242. internal const int DecimalPrecision = 29; // Decimal.DecCalc also uses this value
  243. // SinglePrecision and DoublePrecision represent the maximum number of digits required
  244. // to guarantee that any given Single or Double can roundtrip. Some numbers may require
  245. // less, but none will require more.
  246. private const int SinglePrecision = 9;
  247. private const int DoublePrecision = 17;
  248. private const int DefaultPrecisionExponentialFormat = 6;
  249. private const int ScaleNAN = unchecked((int)0x80000000);
  250. private const int ScaleINF = 0x7FFFFFFF;
  251. private const int MaxUInt32DecDigits = 10;
  252. private const int CharStackBufferSize = 32;
  253. private const string PosNumberFormat = "#";
  254. private static readonly string[] s_singleDigitStringCache = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
  255. private static readonly string[] s_posCurrencyFormats =
  256. {
  257. "$#", "#$", "$ #", "# $"
  258. };
  259. private static readonly string[] s_negCurrencyFormats =
  260. {
  261. "($#)", "-$#", "$-#", "$#-",
  262. "(#$)", "-#$", "#-$", "#$-",
  263. "-# $", "-$ #", "# $-", "$ #-",
  264. "$ -#", "#- $", "($ #)", "(# $)"
  265. };
  266. private static readonly string[] s_posPercentFormats =
  267. {
  268. "# %", "#%", "%#", "% #"
  269. };
  270. private static readonly string[] s_negPercentFormats =
  271. {
  272. "-# %", "-#%", "-%#",
  273. "%-#", "%#-",
  274. "#-%", "#%-",
  275. "-% #", "# %-", "% #-",
  276. "% -#", "#- %"
  277. };
  278. private static readonly string[] s_negNumberFormats =
  279. {
  280. "(#)", "-#", "- #", "#-", "# -",
  281. };
  282. public static unsafe string FormatDecimal(decimal value, ReadOnlySpan<char> format, NumberFormatInfo info)
  283. {
  284. char fmt = ParseFormatSpecifier(format, out int digits);
  285. byte* pDigits = stackalloc byte[DecimalNumberBufferLength];
  286. NumberBuffer number = new NumberBuffer(NumberBufferKind.Decimal, pDigits, DecimalNumberBufferLength);
  287. DecimalToNumber(ref value, ref number);
  288. char* stackPtr = stackalloc char[CharStackBufferSize];
  289. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  290. if (fmt != 0)
  291. {
  292. NumberToString(ref sb, ref number, fmt, digits, info);
  293. }
  294. else
  295. {
  296. NumberToStringFormat(ref sb, ref number, format, info);
  297. }
  298. return sb.ToString();
  299. }
  300. public static unsafe bool TryFormatDecimal(decimal value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten)
  301. {
  302. char fmt = ParseFormatSpecifier(format, out int digits);
  303. byte* pDigits = stackalloc byte[DecimalNumberBufferLength];
  304. NumberBuffer number = new NumberBuffer(NumberBufferKind.Decimal, pDigits, DecimalNumberBufferLength);
  305. DecimalToNumber(ref value, ref number);
  306. char* stackPtr = stackalloc char[CharStackBufferSize];
  307. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  308. if (fmt != 0)
  309. {
  310. NumberToString(ref sb, ref number, fmt, digits, info);
  311. }
  312. else
  313. {
  314. NumberToStringFormat(ref sb, ref number, format, info);
  315. }
  316. return sb.TryCopyTo(destination, out charsWritten);
  317. }
  318. internal static unsafe void DecimalToNumber(ref decimal d, ref NumberBuffer number)
  319. {
  320. byte* buffer = number.GetDigitsPointer();
  321. number.DigitsCount = DecimalPrecision;
  322. number.IsNegative = d.IsNegative;
  323. byte* p = buffer + DecimalPrecision;
  324. while ((d.Mid | d.High) != 0)
  325. {
  326. p = UInt32ToDecChars(p, decimal.DecDivMod1E9(ref d), 9);
  327. }
  328. p = UInt32ToDecChars(p, d.Low, 0);
  329. int i = (int)((buffer + DecimalPrecision) - p);
  330. number.DigitsCount = i;
  331. number.Scale = i - d.Scale;
  332. byte* dst = number.GetDigitsPointer();
  333. while (--i >= 0)
  334. {
  335. *dst++ = *p++;
  336. }
  337. *dst = (byte)('\0');
  338. number.CheckConsistency();
  339. }
  340. public static string FormatDouble(double value, string format, NumberFormatInfo info)
  341. {
  342. Span<char> stackBuffer = stackalloc char[CharStackBufferSize];
  343. var sb = new ValueStringBuilder(stackBuffer);
  344. return FormatDouble(ref sb, value, format, info) ?? sb.ToString();
  345. }
  346. public static bool TryFormatDouble(double value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten)
  347. {
  348. Span<char> stackBuffer = stackalloc char[CharStackBufferSize];
  349. var sb = new ValueStringBuilder(stackBuffer);
  350. string s = FormatDouble(ref sb, value, format, info);
  351. return s != null ?
  352. TryCopyTo(s, destination, out charsWritten) :
  353. sb.TryCopyTo(destination, out charsWritten);
  354. }
  355. private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int precision, NumberFormatInfo info, out bool isSignificantDigits)
  356. {
  357. if (fmt == 0)
  358. {
  359. isSignificantDigits = true;
  360. return precision;
  361. }
  362. int maxDigits = precision;
  363. switch (fmt)
  364. {
  365. case 'C':
  366. case 'c':
  367. {
  368. // The currency format uses the precision specifier to indicate the number of
  369. // decimal digits to format. This defaults to NumberFormatInfo.CurrencyDecimalDigits.
  370. if (precision == -1)
  371. {
  372. precision = info.CurrencyDecimalDigits;
  373. }
  374. isSignificantDigits = false;
  375. break;
  376. }
  377. case 'E':
  378. case 'e':
  379. {
  380. // The exponential format uses the precision specifier to indicate the number of
  381. // decimal digits to format. This defaults to 6. However, the exponential format
  382. // also always formats a single integral digit, so we need to increase the precision
  383. // specifier and treat it as the number of significant digits to account for this.
  384. if (precision == -1)
  385. {
  386. precision = DefaultPrecisionExponentialFormat;
  387. }
  388. precision++;
  389. isSignificantDigits = true;
  390. break;
  391. }
  392. case 'F':
  393. case 'f':
  394. case 'N':
  395. case 'n':
  396. {
  397. // The fixed-point and number formats use the precision specifier to indicate the number
  398. // of decimal digits to format. This defaults to NumberFormatInfo.NumberDecimalDigits.
  399. if (precision == -1)
  400. {
  401. precision = info.NumberDecimalDigits;
  402. }
  403. isSignificantDigits = false;
  404. break;
  405. }
  406. case 'G':
  407. case 'g':
  408. {
  409. // The general format uses the precision specifier to indicate the number of significant
  410. // digits to format. This defaults to the shortest roundtrippable string. Additionally,
  411. // given that we can't return zero significant digits, we treat 0 as returning the shortest
  412. // roundtrippable string as well.
  413. if (precision == 0)
  414. {
  415. precision = -1;
  416. }
  417. isSignificantDigits = true;
  418. break;
  419. }
  420. case 'P':
  421. case 'p':
  422. {
  423. // The percent format uses the precision specifier to indicate the number of
  424. // decimal digits to format. This defaults to NumberFormatInfo.PercentDecimalDigits.
  425. // However, the percent format also always multiplies the number by 100, so we need
  426. // to increase the precision specifier to ensure we get the appropriate number of digits.
  427. if (precision == -1)
  428. {
  429. precision = info.PercentDecimalDigits;
  430. }
  431. precision += 2;
  432. isSignificantDigits = false;
  433. break;
  434. }
  435. case 'R':
  436. case 'r':
  437. {
  438. // The roundtrip format ignores the precision specifier and always returns the shortest
  439. // roundtrippable string.
  440. precision = -1;
  441. isSignificantDigits = true;
  442. break;
  443. }
  444. default:
  445. {
  446. throw new FormatException(SR.Argument_BadFormatSpecifier);
  447. }
  448. }
  449. return maxDigits;
  450. }
  451. /// <summary>Formats the specified value according to the specified format and info.</summary>
  452. /// <returns>
  453. /// Non-null if an existing string can be returned, in which case the builder will be unmodified.
  454. /// Null if no existing string was returned, in which case the formatted output is in the builder.
  455. /// </returns>
  456. private static unsafe string FormatDouble(ref ValueStringBuilder sb, double value, ReadOnlySpan<char> format, NumberFormatInfo info)
  457. {
  458. if (!double.IsFinite(value))
  459. {
  460. if (double.IsNaN(value))
  461. {
  462. return info.NaNSymbol;
  463. }
  464. return double.IsNegative(value) ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol;
  465. }
  466. char fmt = ParseFormatSpecifier(format, out int precision);
  467. byte* pDigits = stackalloc byte[DoubleNumberBufferLength];
  468. NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, pDigits, DoubleNumberBufferLength);
  469. number.IsNegative = double.IsNegative(value);
  470. // We need to track the original precision requested since some formats
  471. // accept values like 0 and others may require additional fixups.
  472. int nMaxDigits = GetFloatingPointMaxDigitsAndPrecision(fmt, ref precision, info, out bool isSignificantDigits);
  473. if ((value != 0.0) && (!isSignificantDigits || !Grisu3.TryRunDouble(value, precision, ref number)))
  474. {
  475. Dragon4Double(value, precision, isSignificantDigits, ref number);
  476. }
  477. number.CheckConsistency();
  478. // When the number is known to be roundtrippable (either because we requested it be, or
  479. // because we know we have enough digits to satisfy roundtrippability), we should validate
  480. // that the number actually roundtrips back to the original result.
  481. Debug.Assert(((precision != -1) && (precision < DoublePrecision)) || (BitConverter.DoubleToInt64Bits(value) == BitConverter.DoubleToInt64Bits(NumberToDouble(ref number))));
  482. if (fmt != 0)
  483. {
  484. if (precision == -1)
  485. {
  486. Debug.Assert((fmt == 'G') || (fmt == 'g') || (fmt == 'R') || (fmt == 'r'));
  487. // For the roundtrip and general format specifiers, when returning the shortest roundtrippable
  488. // string, we need to update the maximum number of digits to be the greater of number.DigitsCount
  489. // or DoublePrecision. This ensures that we continue returning "pretty" strings for values with
  490. // less digits. One example this fixes is "-60", which would otherwise be formatted as "-6E+01"
  491. // since DigitsCount would be 1 and the formatter would almost immediately switch to scientific notation.
  492. nMaxDigits = Math.Max(number.DigitsCount, DoublePrecision);
  493. }
  494. NumberToString(ref sb, ref number, fmt, nMaxDigits, info);
  495. }
  496. else
  497. {
  498. NumberToStringFormat(ref sb, ref number, format, info);
  499. }
  500. return null;
  501. }
  502. public static string FormatSingle(float value, string format, NumberFormatInfo info)
  503. {
  504. Span<char> stackBuffer = stackalloc char[CharStackBufferSize];
  505. var sb = new ValueStringBuilder(stackBuffer);
  506. return FormatSingle(ref sb, value, format, info) ?? sb.ToString();
  507. }
  508. public static bool TryFormatSingle(float value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten)
  509. {
  510. Span<char> stackBuffer = stackalloc char[CharStackBufferSize];
  511. var sb = new ValueStringBuilder(stackBuffer);
  512. string s = FormatSingle(ref sb, value, format, info);
  513. return s != null ?
  514. TryCopyTo(s, destination, out charsWritten) :
  515. sb.TryCopyTo(destination, out charsWritten);
  516. }
  517. /// <summary>Formats the specified value according to the specified format and info.</summary>
  518. /// <returns>
  519. /// Non-null if an existing string can be returned, in which case the builder will be unmodified.
  520. /// Null if no existing string was returned, in which case the formatted output is in the builder.
  521. /// </returns>
  522. private static unsafe string FormatSingle(ref ValueStringBuilder sb, float value, ReadOnlySpan<char> format, NumberFormatInfo info)
  523. {
  524. if (!float.IsFinite(value))
  525. {
  526. if (float.IsNaN(value))
  527. {
  528. return info.NaNSymbol;
  529. }
  530. return float.IsNegative(value) ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol;
  531. }
  532. char fmt = ParseFormatSpecifier(format, out int precision);
  533. byte* pDigits = stackalloc byte[SingleNumberBufferLength];
  534. NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, pDigits, SingleNumberBufferLength);
  535. number.IsNegative = float.IsNegative(value);
  536. // We need to track the original precision requested since some formats
  537. // accept values like 0 and others may require additional fixups.
  538. int nMaxDigits = GetFloatingPointMaxDigitsAndPrecision(fmt, ref precision, info, out bool isSignificantDigits);
  539. if ((value != 0.0f) && (!isSignificantDigits || !Grisu3.TryRunSingle(value, precision, ref number)))
  540. {
  541. Dragon4Single(value, precision, isSignificantDigits, ref number);
  542. }
  543. number.CheckConsistency();
  544. // When the number is known to be roundtrippable (either because we requested it be, or
  545. // because we know we have enough digits to satisfy roundtrippability), we should validate
  546. // that the number actually roundtrips back to the original result.
  547. Debug.Assert(((precision != -1) && (precision < SinglePrecision)) || (BitConverter.SingleToInt32Bits(value) == BitConverter.SingleToInt32Bits(NumberToSingle(ref number))));
  548. if (fmt != 0)
  549. {
  550. if (precision == -1)
  551. {
  552. Debug.Assert((fmt == 'G') || (fmt == 'g') || (fmt == 'R') || (fmt == 'r'));
  553. // For the roundtrip and general format specifiers, when returning the shortest roundtrippable
  554. // string, we need to update the maximum number of digits to be the greater of number.DigitsCount
  555. // or SinglePrecision. This ensures that we continue returning "pretty" strings for values with
  556. // less digits. One example this fixes is "-60", which would otherwise be formatted as "-6E+01"
  557. // since DigitsCount would be 1 and the formatter would almost immediately switch to scientific notation.
  558. nMaxDigits = Math.Max(number.DigitsCount, SinglePrecision);
  559. }
  560. NumberToString(ref sb, ref number, fmt, nMaxDigits, info);
  561. }
  562. else
  563. {
  564. NumberToStringFormat(ref sb, ref number, format, info);
  565. }
  566. return null;
  567. }
  568. private static bool TryCopyTo(string source, Span<char> destination, out int charsWritten)
  569. {
  570. Debug.Assert(source != null);
  571. if (source.AsSpan().TryCopyTo(destination))
  572. {
  573. charsWritten = source.Length;
  574. return true;
  575. }
  576. charsWritten = 0;
  577. return false;
  578. }
  579. public static unsafe string FormatInt32(int value, ReadOnlySpan<char> format, IFormatProvider provider)
  580. {
  581. // Fast path for default format with a non-negative value
  582. if (value >= 0 && format.Length == 0)
  583. {
  584. return UInt32ToDecStr((uint)value, digits: -1);
  585. }
  586. char fmt = ParseFormatSpecifier(format, out int digits);
  587. char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
  588. if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
  589. {
  590. return value >= 0 ?
  591. UInt32ToDecStr((uint)value, digits) :
  592. NegativeInt32ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign);
  593. }
  594. else if (fmtUpper == 'X')
  595. {
  596. // The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
  597. // hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code produces lowercase.
  598. return Int32ToHexStr(value, (char)(fmt - ('X' - 'A' + 10)), digits);
  599. }
  600. else
  601. {
  602. NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
  603. byte* pDigits = stackalloc byte[Int32NumberBufferLength];
  604. NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, Int32NumberBufferLength);
  605. Int32ToNumber(value, ref number);
  606. char* stackPtr = stackalloc char[CharStackBufferSize];
  607. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  608. if (fmt != 0)
  609. {
  610. NumberToString(ref sb, ref number, fmt, digits, info);
  611. }
  612. else
  613. {
  614. NumberToStringFormat(ref sb, ref number, format, info);
  615. }
  616. return sb.ToString();
  617. }
  618. }
  619. public static unsafe bool TryFormatInt32(int value, ReadOnlySpan<char> format, IFormatProvider provider, Span<char> destination, out int charsWritten)
  620. {
  621. // Fast path for default format with a non-negative value
  622. if (value >= 0 && format.Length == 0)
  623. {
  624. return TryUInt32ToDecStr((uint)value, digits: -1, destination, out charsWritten);
  625. }
  626. char fmt = ParseFormatSpecifier(format, out int digits);
  627. char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
  628. if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
  629. {
  630. return value >= 0 ?
  631. TryUInt32ToDecStr((uint)value, digits, destination, out charsWritten) :
  632. TryNegativeInt32ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten);
  633. }
  634. else if (fmtUpper == 'X')
  635. {
  636. // The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
  637. // hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code produces lowercase.
  638. return TryInt32ToHexStr(value, (char)(fmt - ('X' - 'A' + 10)), digits, destination, out charsWritten);
  639. }
  640. else
  641. {
  642. NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
  643. byte* pDigits = stackalloc byte[Int32NumberBufferLength];
  644. NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, Int32NumberBufferLength);
  645. Int32ToNumber(value, ref number);
  646. char* stackPtr = stackalloc char[CharStackBufferSize];
  647. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  648. if (fmt != 0)
  649. {
  650. NumberToString(ref sb, ref number, fmt, digits, info);
  651. }
  652. else
  653. {
  654. NumberToStringFormat(ref sb, ref number, format, info);
  655. }
  656. return sb.TryCopyTo(destination, out charsWritten);
  657. }
  658. }
  659. public static unsafe string FormatUInt32(uint value, ReadOnlySpan<char> format, IFormatProvider provider)
  660. {
  661. // Fast path for default format
  662. if (format.Length == 0)
  663. {
  664. return UInt32ToDecStr(value, digits: -1);
  665. }
  666. char fmt = ParseFormatSpecifier(format, out int digits);
  667. char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
  668. if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
  669. {
  670. return UInt32ToDecStr(value, digits);
  671. }
  672. else if (fmtUpper == 'X')
  673. {
  674. // The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
  675. // hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code produces lowercase.
  676. return Int32ToHexStr((int)value, (char)(fmt - ('X' - 'A' + 10)), digits);
  677. }
  678. else
  679. {
  680. NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
  681. byte* pDigits = stackalloc byte[UInt32NumberBufferLength];
  682. NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, UInt32NumberBufferLength);
  683. UInt32ToNumber(value, ref number);
  684. char* stackPtr = stackalloc char[CharStackBufferSize];
  685. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  686. if (fmt != 0)
  687. {
  688. NumberToString(ref sb, ref number, fmt, digits, info);
  689. }
  690. else
  691. {
  692. NumberToStringFormat(ref sb, ref number, format, info);
  693. }
  694. return sb.ToString();
  695. }
  696. }
  697. public static unsafe bool TryFormatUInt32(uint value, ReadOnlySpan<char> format, IFormatProvider provider, Span<char> destination, out int charsWritten)
  698. {
  699. // Fast path for default format
  700. if (format.Length == 0)
  701. {
  702. return TryUInt32ToDecStr(value, digits: -1, destination, out charsWritten);
  703. }
  704. char fmt = ParseFormatSpecifier(format, out int digits);
  705. char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
  706. if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
  707. {
  708. return TryUInt32ToDecStr(value, digits, destination, out charsWritten);
  709. }
  710. else if (fmtUpper == 'X')
  711. {
  712. // The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
  713. // hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code produces lowercase.
  714. return TryInt32ToHexStr((int)value, (char)(fmt - ('X' - 'A' + 10)), digits, destination, out charsWritten);
  715. }
  716. else
  717. {
  718. NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
  719. byte* pDigits = stackalloc byte[UInt32NumberBufferLength];
  720. NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, UInt32NumberBufferLength);
  721. UInt32ToNumber(value, ref number);
  722. char* stackPtr = stackalloc char[CharStackBufferSize];
  723. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  724. if (fmt != 0)
  725. {
  726. NumberToString(ref sb, ref number, fmt, digits, info);
  727. }
  728. else
  729. {
  730. NumberToStringFormat(ref sb, ref number, format, info);
  731. }
  732. return sb.TryCopyTo(destination, out charsWritten);
  733. }
  734. }
  735. public static unsafe string FormatInt64(long value, ReadOnlySpan<char> format, IFormatProvider provider)
  736. {
  737. // Fast path for default format with a non-negative value
  738. if (value >= 0 && format.Length == 0)
  739. {
  740. return UInt64ToDecStr((ulong)value, digits: -1);
  741. }
  742. char fmt = ParseFormatSpecifier(format, out int digits);
  743. char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
  744. if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
  745. {
  746. return value >= 0 ?
  747. UInt64ToDecStr((ulong)value, digits) :
  748. NegativeInt64ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign);
  749. }
  750. else if (fmtUpper == 'X')
  751. {
  752. // The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
  753. // hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code
  754. // produces lowercase.
  755. return Int64ToHexStr(value, (char)(fmt - ('X' - 'A' + 10)), digits);
  756. }
  757. else
  758. {
  759. NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
  760. byte* pDigits = stackalloc byte[Int64NumberBufferLength];
  761. NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, Int64NumberBufferLength);
  762. Int64ToNumber(value, ref number);
  763. char* stackPtr = stackalloc char[CharStackBufferSize];
  764. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  765. if (fmt != 0)
  766. {
  767. NumberToString(ref sb, ref number, fmt, digits, info);
  768. }
  769. else
  770. {
  771. NumberToStringFormat(ref sb, ref number, format, info);
  772. }
  773. return sb.ToString();
  774. }
  775. }
  776. public static unsafe bool TryFormatInt64(long value, ReadOnlySpan<char> format, IFormatProvider provider, Span<char> destination, out int charsWritten)
  777. {
  778. // Fast path for default format with a non-negative value
  779. if (value >= 0 && format.Length == 0)
  780. {
  781. return TryUInt64ToDecStr((ulong)value, digits: -1, destination, out charsWritten);
  782. }
  783. char fmt = ParseFormatSpecifier(format, out int digits);
  784. char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
  785. if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
  786. {
  787. return value >= 0 ?
  788. TryUInt64ToDecStr((ulong)value, digits, destination, out charsWritten) :
  789. TryNegativeInt64ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten);
  790. }
  791. else if (fmtUpper == 'X')
  792. {
  793. // The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
  794. // hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code
  795. // produces lowercase.
  796. return TryInt64ToHexStr(value, (char)(fmt - ('X' - 'A' + 10)), digits, destination, out charsWritten);
  797. }
  798. else
  799. {
  800. NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
  801. byte* pDigits = stackalloc byte[Int64NumberBufferLength];
  802. NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, Int64NumberBufferLength);
  803. Int64ToNumber(value, ref number);
  804. char* stackPtr = stackalloc char[CharStackBufferSize];
  805. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  806. if (fmt != 0)
  807. {
  808. NumberToString(ref sb, ref number, fmt, digits, info);
  809. }
  810. else
  811. {
  812. NumberToStringFormat(ref sb, ref number, format, info);
  813. }
  814. return sb.TryCopyTo(destination, out charsWritten);
  815. }
  816. }
  817. public static unsafe string FormatUInt64(ulong value, ReadOnlySpan<char> format, IFormatProvider provider)
  818. {
  819. // Fast path for default format
  820. if (format.Length == 0)
  821. {
  822. return UInt64ToDecStr(value, digits: -1);
  823. }
  824. char fmt = ParseFormatSpecifier(format, out int digits);
  825. char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
  826. if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
  827. {
  828. return UInt64ToDecStr(value, digits);
  829. }
  830. else if (fmtUpper == 'X')
  831. {
  832. // The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
  833. // hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code
  834. // produces lowercase.
  835. return Int64ToHexStr((long)value, (char)(fmt - ('X' - 'A' + 10)), digits);
  836. }
  837. else
  838. {
  839. NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
  840. byte* pDigits = stackalloc byte[UInt64NumberBufferLength];
  841. NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, UInt64NumberBufferLength);
  842. UInt64ToNumber(value, ref number);
  843. char* stackPtr = stackalloc char[CharStackBufferSize];
  844. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  845. if (fmt != 0)
  846. {
  847. NumberToString(ref sb, ref number, fmt, digits, info);
  848. }
  849. else
  850. {
  851. NumberToStringFormat(ref sb, ref number, format, info);
  852. }
  853. return sb.ToString();
  854. }
  855. }
  856. public static unsafe bool TryFormatUInt64(ulong value, ReadOnlySpan<char> format, IFormatProvider provider, Span<char> destination, out int charsWritten)
  857. {
  858. // Fast path for default format
  859. if (format.Length == 0)
  860. {
  861. return TryUInt64ToDecStr(value, digits: -1, destination, out charsWritten);
  862. }
  863. char fmt = ParseFormatSpecifier(format, out int digits);
  864. char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
  865. if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
  866. {
  867. return TryUInt64ToDecStr(value, digits, destination, out charsWritten);
  868. }
  869. else if (fmtUpper == 'X')
  870. {
  871. // The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
  872. // hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code
  873. // produces lowercase.
  874. return TryInt64ToHexStr((long)value, (char)(fmt - ('X' - 'A' + 10)), digits, destination, out charsWritten);
  875. }
  876. else
  877. {
  878. NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
  879. byte* pDigits = stackalloc byte[UInt64NumberBufferLength];
  880. NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, UInt64NumberBufferLength);
  881. UInt64ToNumber(value, ref number);
  882. char* stackPtr = stackalloc char[CharStackBufferSize];
  883. ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
  884. if (fmt != 0)
  885. {
  886. NumberToString(ref sb, ref number, fmt, digits, info);
  887. }
  888. else
  889. {
  890. NumberToStringFormat(ref sb, ref number, format, info);
  891. }
  892. return sb.TryCopyTo(destination, out charsWritten);
  893. }
  894. }
  895. [MethodImpl(MethodImplOptions.AggressiveInlining)] // called from only one location
  896. private static unsafe void Int32ToNumber(int value, ref NumberBuffer number)
  897. {
  898. number.DigitsCount = Int32Precision;
  899. if (value >= 0)
  900. {
  901. number.IsNegative = false;
  902. }
  903. else
  904. {
  905. number.IsNegative = true;
  906. value = -value;
  907. }
  908. byte* buffer = number.GetDigitsPointer();
  909. byte* p = UInt32ToDecChars(buffer + Int32Precision, (uint)value, 0);
  910. int i = (int)(buffer + Int32Precision - p);
  911. number.DigitsCount = i;
  912. number.Scale = i;
  913. byte* dst = number.GetDigitsPointer();
  914. while (--i >= 0)
  915. *dst++ = *p++;
  916. *dst = (byte)('\0');
  917. number.CheckConsistency();
  918. }
  919. private static unsafe string NegativeInt32ToDecStr(int value, int digits, string sNegative)
  920. {
  921. Debug.Assert(value < 0);
  922. if (digits < 1)
  923. digits = 1;
  924. int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((uint)(-value))) + sNegative.Length;
  925. string result = string.FastAllocateString(bufferLength);
  926. fixed (char* buffer = result)
  927. {
  928. char* p = UInt32ToDecChars(buffer + bufferLength, (uint)(-value), digits);
  929. Debug.Assert(p == buffer + sNegative.Length);
  930. for (int i = sNegative.Length - 1; i >= 0; i--)
  931. {
  932. *(--p) = sNegative[i];
  933. }
  934. Debug.Assert(p == buffer);
  935. }
  936. return result;
  937. }
  938. private static unsafe bool TryNegativeInt32ToDecStr(int value, int digits, string sNegative, Span<char> destination, out int charsWritten)
  939. {
  940. Debug.Assert(value < 0);
  941. if (digits < 1)
  942. digits = 1;
  943. int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((uint)(-value))) + sNegative.Length;
  944. if (bufferLength > destination.Length)
  945. {
  946. charsWritten = 0;
  947. return false;
  948. }
  949. charsWritten = bufferLength;
  950. fixed (char* buffer = &MemoryMarshal.GetReference(destination))
  951. {
  952. char* p = UInt32ToDecChars(buffer + bufferLength, (uint)(-value), digits);
  953. Debug.Assert(p == buffer + sNegative.Length);
  954. for (int i = sNegative.Length - 1; i >= 0; i--)
  955. {
  956. *(--p) = sNegative[i];
  957. }
  958. Debug.Assert(p == buffer);
  959. }
  960. return true;
  961. }
  962. private static unsafe string Int32ToHexStr(int value, char hexBase, int digits)
  963. {
  964. if (digits < 1)
  965. digits = 1;
  966. int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((uint)value));
  967. string result = string.FastAllocateString(bufferLength);
  968. fixed (char* buffer = result)
  969. {
  970. char* p = Int32ToHexChars(buffer + bufferLength, (uint)value, hexBase, digits);
  971. Debug.Assert(p == buffer);
  972. }
  973. return result;
  974. }
  975. private static unsafe bool TryInt32ToHexStr(int value, char hexBase, int digits, Span<char> destination, out int charsWritten)
  976. {
  977. if (digits < 1)
  978. digits = 1;
  979. int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((uint)value));
  980. if (bufferLength > destination.Length)
  981. {
  982. charsWritten = 0;
  983. return false;
  984. }
  985. charsWritten = bufferLength;
  986. fixed (char* buffer = &MemoryMarshal.GetReference(destination))
  987. {
  988. char* p = Int32ToHexChars(buffer + bufferLength, (uint)value, hexBase, digits);
  989. Debug.Assert(p == buffer);
  990. }
  991. return true;
  992. }
  993. private static unsafe char* Int32ToHexChars(char* buffer, uint value, int hexBase, int digits)
  994. {
  995. while (--digits >= 0 || value != 0)
  996. {
  997. byte digit = (byte)(value & 0xF);
  998. *(--buffer) = (char)(digit + (digit < 10 ? (byte)'0' : hexBase));
  999. value >>= 4;
  1000. }
  1001. return buffer;
  1002. }
  1003. [MethodImpl(MethodImplOptions.AggressiveInlining)] // called from only one location
  1004. private static unsafe void UInt32ToNumber(uint value, ref NumberBuffer number)
  1005. {
  1006. number.DigitsCount = UInt32Precision;
  1007. number.IsNegative = false;
  1008. byte* buffer = number.GetDigitsPointer();
  1009. byte* p = UInt32ToDecChars(buffer + UInt32Precision, value, 0);
  1010. int i = (int)(buffer + UInt32Precision - p);
  1011. number.DigitsCount = i;
  1012. number.Scale = i;
  1013. byte* dst = number.GetDigitsPointer();
  1014. while (--i >= 0)
  1015. *dst++ = *p++;
  1016. *dst = (byte)('\0');
  1017. number.CheckConsistency();
  1018. }
  1019. internal static unsafe byte* UInt32ToDecChars(byte* bufferEnd, uint value, int digits)
  1020. {
  1021. while (--digits >= 0 || value != 0)
  1022. {
  1023. // TODO https://github.com/dotnet/coreclr/issues/3439
  1024. uint newValue = value / 10;
  1025. *(--bufferEnd) = (byte)(value - (newValue * 10) + '0');
  1026. value = newValue;
  1027. }
  1028. return bufferEnd;
  1029. }
  1030. internal static unsafe char* UInt32ToDecChars(char* bufferEnd, uint value, int digits)
  1031. {
  1032. while (--digits >= 0 || value != 0)
  1033. {
  1034. // TODO https://github.com/dotnet/coreclr/issues/3439
  1035. uint newValue = value / 10;
  1036. *(--bufferEnd) = (char)(value - (newValue * 10) + '0');
  1037. value = newValue;
  1038. }
  1039. return bufferEnd;
  1040. }
  1041. private static unsafe string UInt32ToDecStr(uint value, int digits)
  1042. {
  1043. int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value));
  1044. // For single-digit values that are very common, especially 0 and 1, just return cached strings.
  1045. if (bufferLength == 1)
  1046. {
  1047. return s_singleDigitStringCache[value];
  1048. }
  1049. string result = string.FastAllocateString(bufferLength);
  1050. fixed (char* buffer = result)
  1051. {
  1052. char* p = buffer + bufferLength;
  1053. if (digits <= 1)
  1054. {
  1055. do
  1056. {
  1057. // TODO https://github.com/dotnet/coreclr/issues/3439
  1058. uint div = value / 10;
  1059. *(--p) = (char)('0' + value - (div * 10));
  1060. value = div;
  1061. }
  1062. while (value != 0);
  1063. }
  1064. else
  1065. {
  1066. p = UInt32ToDecChars(p, value, digits);
  1067. }
  1068. Debug.Assert(p == buffer);
  1069. }
  1070. return result;
  1071. }
  1072. private static unsafe bool TryUInt32ToDecStr(uint value, int digits, Span<char> destination, out int charsWritten)
  1073. {
  1074. int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value));
  1075. if (bufferLength > destination.Length)
  1076. {
  1077. charsWritten = 0;
  1078. return false;
  1079. }
  1080. charsWritten = bufferLength;
  1081. fixed (char* buffer = &MemoryMarshal.GetReference(destination))
  1082. {
  1083. char* p = buffer + bufferLength;
  1084. if (digits <= 1)
  1085. {
  1086. do
  1087. {
  1088. // TODO https://github.com/dotnet/coreclr/issues/3439
  1089. uint div = value / 10;
  1090. *(--p) = (char)('0' + value - (div * 10));
  1091. value = div;
  1092. }
  1093. while (value != 0);
  1094. }
  1095. else
  1096. {
  1097. p = UInt32ToDecChars(p, value, digits);
  1098. }
  1099. Debug.Assert(p == buffer);
  1100. }
  1101. return true;
  1102. }
  1103. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1104. private static unsafe bool TryCopyTo(char* src, int length, Span<char> destination, out int charsWritten)
  1105. {
  1106. if (new ReadOnlySpan<char>(src, length).TryCopyTo(destination))
  1107. {
  1108. charsWritten = length;
  1109. return true;
  1110. }
  1111. else
  1112. {
  1113. charsWritten = 0;
  1114. return false;
  1115. }
  1116. }
  1117. private static unsafe void Int64ToNumber(long input, ref NumberBuffer number)
  1118. {
  1119. ulong value = (ulong)input;
  1120. number.IsNegative = input < 0;
  1121. number.DigitsCount = Int64Precision;
  1122. if (number.IsNegative)
  1123. {
  1124. value = (ulong)(-input);
  1125. }
  1126. byte* buffer = number.GetDigitsPointer();
  1127. byte* p = buffer + Int64Precision;
  1128. while (High32(value) != 0)
  1129. p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
  1130. p = UInt32ToDecChars(p, Low32(value), 0);
  1131. int i = (int)(buffer + Int64Precision - p);
  1132. number.DigitsCount = i;
  1133. number.Scale = i;
  1134. byte* dst = number.GetDigitsPointer();
  1135. while (--i >= 0)
  1136. *dst++ = *p++;
  1137. *dst = (byte)('\0');
  1138. number.CheckConsistency();
  1139. }
  1140. private static unsafe string NegativeInt64ToDecStr(long input, int digits, string sNegative)
  1141. {
  1142. Debug.Assert(input < 0);
  1143. if (digits < 1)
  1144. {
  1145. digits = 1;
  1146. }
  1147. ulong value = (ulong)(-input);
  1148. int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)) + sNegative.Length;
  1149. string result = string.FastAllocateString(bufferLength);
  1150. fixed (char* buffer = result)
  1151. {
  1152. char* p = buffer + bufferLength;
  1153. while (High32(value) != 0)
  1154. {
  1155. p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
  1156. digits -= 9;
  1157. }
  1158. p = UInt32ToDecChars(p, Low32(value), digits);
  1159. Debug.Assert(p == buffer + sNegative.Length);
  1160. for (int i = sNegative.Length - 1; i >= 0; i--)
  1161. {
  1162. *(--p) = sNegative[i];
  1163. }
  1164. Debug.Assert(p == buffer);
  1165. }
  1166. return result;
  1167. }
  1168. private static unsafe bool TryNegativeInt64ToDecStr(long input, int digits, string sNegative, Span<char> destination, out int charsWritten)
  1169. {
  1170. Debug.Assert(input < 0);
  1171. if (digits < 1)
  1172. {
  1173. digits = 1;
  1174. }
  1175. ulong value = (ulong)(-input);
  1176. int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((ulong)(-input))) + sNegative.Length;
  1177. if (bufferLength > destination.Length)
  1178. {
  1179. charsWritten = 0;
  1180. return false;
  1181. }
  1182. charsWritten = bufferLength;
  1183. fixed (char* buffer = &MemoryMarshal.GetReference(destination))
  1184. {
  1185. char* p = buffer + bufferLength;
  1186. while (High32(value) != 0)
  1187. {
  1188. p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
  1189. digits -= 9;
  1190. }
  1191. p = UInt32ToDecChars(p, Low32(value), digits);
  1192. Debug.Assert(p == buffer + sNegative.Length);
  1193. for (int i = sNegative.Length - 1; i >= 0; i--)
  1194. {
  1195. *(--p) = sNegative[i];
  1196. }
  1197. Debug.Assert(p == buffer);
  1198. }
  1199. return true;
  1200. }
  1201. private static unsafe string Int64ToHexStr(long value, char hexBase, int digits)
  1202. {
  1203. int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((ulong)value));
  1204. string result = string.FastAllocateString(bufferLength);
  1205. fixed (char* buffer = result)
  1206. {
  1207. char* p = buffer + bufferLength;
  1208. if (High32((ulong)value) != 0)
  1209. {
  1210. p = Int32ToHexChars(p, Low32((ulong)value), hexBase, 8);
  1211. p = Int32ToHexChars(p, High32((ulong)value), hexBase, digits - 8);
  1212. }
  1213. else
  1214. {
  1215. p = Int32ToHexChars(p, Low32((ulong)value), hexBase, Math.Max(digits, 1));
  1216. }
  1217. Debug.Assert(p == buffer);
  1218. }
  1219. return result;
  1220. }
  1221. private static unsafe bool TryInt64ToHexStr(long value, char hexBase, int digits, Span<char> destination, out int charsWritten)
  1222. {
  1223. int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((ulong)value));
  1224. if (bufferLength > destination.Length)
  1225. {
  1226. charsWritten = 0;
  1227. return false;
  1228. }
  1229. charsWritten = bufferLength;
  1230. fixed (char* buffer = &MemoryMarshal.GetReference(destination))
  1231. {
  1232. char* p = buffer + bufferLength;
  1233. if (High32((ulong)value) != 0)
  1234. {
  1235. p = Int32ToHexChars(p, Low32((ulong)value), hexBase, 8);
  1236. p = Int32ToHexChars(p, High32((ulong)value), hexBase, digits - 8);
  1237. }
  1238. else
  1239. {
  1240. p = Int32ToHexChars(p, Low32((ulong)value), hexBase, Math.Max(digits, 1));
  1241. }
  1242. Debug.Assert(p == buffer);
  1243. }
  1244. return true;
  1245. }
  1246. private static unsafe void UInt64ToNumber(ulong value, ref NumberBuffer number)
  1247. {
  1248. number.DigitsCount = UInt64Precision;
  1249. number.IsNegative = false;
  1250. byte* buffer = number.GetDigitsPointer();
  1251. byte* p = buffer + UInt64Precision;
  1252. while (High32(value) != 0)
  1253. p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
  1254. p = UInt32ToDecChars(p, Low32(value), 0);
  1255. int i = (int)(buffer + UInt64Precision - p);
  1256. number.DigitsCount = i;
  1257. number.Scale = i;
  1258. byte* dst = number.GetDigitsPointer();
  1259. while (--i >= 0)
  1260. *dst++ = *p++;
  1261. *dst = (byte)('\0');
  1262. number.CheckConsistency();
  1263. }
  1264. private static unsafe string UInt64ToDecStr(ulong value, int digits)
  1265. {
  1266. if (digits < 1)
  1267. digits = 1;
  1268. int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value));
  1269. // For single-digit values that are very common, especially 0 and 1, just return cached strings.
  1270. if (bufferLength == 1)
  1271. {
  1272. return s_singleDigitStringCache[value];
  1273. }
  1274. string result = string.FastAllocateString(bufferLength);
  1275. fixed (char* buffer = result)
  1276. {
  1277. char* p = buffer + bufferLength;
  1278. while (High32(value) != 0)
  1279. {
  1280. p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
  1281. digits -= 9;
  1282. }
  1283. p = UInt32ToDecChars(p, Low32(value), digits);
  1284. Debug.Assert(p == buffer);
  1285. }
  1286. return result;
  1287. }
  1288. private static unsafe bool TryUInt64ToDecStr(ulong value, int digits, Span<char> destination, out int charsWritten)
  1289. {
  1290. if (digits < 1)
  1291. digits = 1;
  1292. int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value));
  1293. if (bufferLength > destination.Length)
  1294. {
  1295. charsWritten = 0;
  1296. return false;
  1297. }
  1298. charsWritten = bufferLength;
  1299. fixed (char* buffer = &MemoryMarshal.GetReference(destination))
  1300. {
  1301. char* p = buffer + bufferLength;
  1302. while (High32(value) != 0)
  1303. {
  1304. p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
  1305. digits -= 9;
  1306. }
  1307. p = UInt32ToDecChars(p, Low32(value), digits);
  1308. Debug.Assert(p == buffer);
  1309. }
  1310. return true;
  1311. }
  1312. internal static unsafe char ParseFormatSpecifier(ReadOnlySpan<char> format, out int digits)
  1313. {
  1314. char c = default;
  1315. if (format.Length > 0)
  1316. {
  1317. // If the format begins with a symbol, see if it's a standard format
  1318. // with or without a specified number of digits.
  1319. c = format[0];
  1320. if ((uint)(c - 'A') <= 'Z' - 'A' ||
  1321. (uint)(c - 'a') <= 'z' - 'a')
  1322. {
  1323. // Fast path for sole symbol, e.g. "D"
  1324. if (format.Length == 1)
  1325. {
  1326. digits = -1;
  1327. return c;
  1328. }
  1329. if (format.Length == 2)
  1330. {
  1331. // Fast path for symbol and single digit, e.g. "X4"
  1332. int d = format[1] - '0';
  1333. if ((uint)d < 10)
  1334. {
  1335. digits = d;
  1336. return c;
  1337. }
  1338. }
  1339. else if (format.Length == 3)
  1340. {
  1341. // Fast path for symbol and double digit, e.g. "F12"
  1342. int d1 = format[1] - '0', d2 = format[2] - '0';
  1343. if ((uint)d1 < 10 && (uint)d2 < 10)
  1344. {
  1345. digits = d1 * 10 + d2;
  1346. return c;
  1347. }
  1348. }
  1349. // Fallback for symbol and any length digits. The digits value must be >= 0 && <= 99,
  1350. // but it can begin with any number of 0s, and thus we may need to check more than two
  1351. // digits. Further, for compat, we need to stop when we hit a null char.
  1352. int n = 0;
  1353. int i = 1;
  1354. while (i < format.Length && (((uint)format[i] - '0') < 10) && n < 10)
  1355. {
  1356. n = (n * 10) + format[i++] - '0';
  1357. }
  1358. // If we're at the end of the digits rather than having stopped because we hit something
  1359. // other than a digit or overflowed, return the standard format info.
  1360. if (i == format.Length || format[i] == '\0')
  1361. {
  1362. digits = n;
  1363. return c;
  1364. }
  1365. }
  1366. }
  1367. // Default empty format to be "G"; custom format is signified with '\0'.
  1368. digits = -1;
  1369. return format.Length == 0 || c == '\0' ? // For compat, treat '\0' as the end of the specifier, even if the specifier extends beyond it.
  1370. 'G' :
  1371. '\0';
  1372. }
  1373. internal static unsafe void NumberToString(ref ValueStringBuilder sb, ref NumberBuffer number, char format, int nMaxDigits, NumberFormatInfo info)
  1374. {
  1375. number.CheckConsistency();
  1376. switch (format)
  1377. {
  1378. case 'C':
  1379. case 'c':
  1380. {
  1381. if (nMaxDigits < 0)
  1382. nMaxDigits = info.CurrencyDecimalDigits;
  1383. RoundNumber(ref number, number.Scale + nMaxDigits); // Don't change this line to use digPos since digCount could have its sign changed.
  1384. FormatCurrency(ref sb, ref number, nMaxDigits, info);
  1385. break;
  1386. }
  1387. case 'F':
  1388. case 'f':
  1389. {
  1390. if (nMaxDigits < 0)
  1391. nMaxDigits = info.NumberDecimalDigits;
  1392. RoundNumber(ref number, number.Scale + nMaxDigits);
  1393. if (number.IsNegative)
  1394. sb.Append(info.NegativeSign);
  1395. FormatFixed(ref sb, ref number, nMaxDigits, info, null, info.NumberDecimalSeparator, null);
  1396. break;
  1397. }
  1398. case 'N':
  1399. case 'n':
  1400. {
  1401. if (nMaxDigits < 0)
  1402. nMaxDigits = info.NumberDecimalDigits; // Since we are using digits in our calculation
  1403. RoundNumber(ref number, number.Scale + nMaxDigits);
  1404. FormatNumber(ref sb, ref number, nMaxDigits, info);
  1405. break;
  1406. }
  1407. case 'E':
  1408. case 'e':
  1409. {
  1410. if (nMaxDigits < 0)
  1411. nMaxDigits = DefaultPrecisionExponentialFormat;
  1412. nMaxDigits++;
  1413. RoundNumber(ref number, nMaxDigits);
  1414. if (number.IsNegative)
  1415. sb.Append(info.NegativeSign);
  1416. FormatScientific(ref sb, ref number, nMaxDigits, info, format);
  1417. break;
  1418. }
  1419. case 'G':
  1420. case 'g':
  1421. {
  1422. bool noRounding = false;
  1423. if (nMaxDigits < 1)
  1424. {
  1425. if ((number.Kind == NumberBufferKind.Decimal) && (nMaxDigits == -1))
  1426. {
  1427. noRounding = true; // Turn off rounding for ECMA compliance to output trailing 0's after decimal as significant
  1428. if (number.Digits[0] == 0)
  1429. {
  1430. // -0 should be formatted as 0 for decimal. This is normally handled by RoundNumber (which we are skipping)
  1431. goto SkipSign;
  1432. }
  1433. goto SkipRounding;
  1434. }
  1435. else
  1436. {
  1437. // This ensures that the PAL code pads out to the correct place even when we use the default precision
  1438. nMaxDigits = number.DigitsCount;
  1439. }
  1440. }
  1441. RoundNumber(ref number, nMaxDigits);
  1442. SkipRounding:
  1443. if (number.IsNegative)
  1444. sb.Append(info.NegativeSign);
  1445. SkipSign:
  1446. FormatGeneral(ref sb, ref number, nMaxDigits, info, (char)(format - ('G' - 'E')), noRounding);
  1447. break;
  1448. }
  1449. case 'P':
  1450. case 'p':
  1451. {
  1452. if (nMaxDigits < 0)
  1453. nMaxDigits = info.PercentDecimalDigits;
  1454. number.Scale += 2;
  1455. RoundNumber(ref number, number.Scale + nMaxDigits);
  1456. FormatPercent(ref sb, ref number, nMaxDigits, info);
  1457. break;
  1458. }
  1459. case 'R':
  1460. case 'r':
  1461. {
  1462. format = (char)(format - ('R' - 'G'));
  1463. Debug.Assert((format == 'G') || (format == 'g'));
  1464. goto case 'G';
  1465. }
  1466. default:
  1467. throw new FormatException(SR.Argument_BadFormatSpecifier);
  1468. }
  1469. }
  1470. internal static unsafe void NumberToStringFormat(ref ValueStringBuilder sb, ref NumberBuffer number, ReadOnlySpan<char> format, NumberFormatInfo info)
  1471. {
  1472. number.CheckConsistency();
  1473. int digitCount;
  1474. int decimalPos;
  1475. int firstDigit;
  1476. int lastDigit;
  1477. int digPos;
  1478. bool scientific;
  1479. int thousandPos;
  1480. int thousandCount = 0;
  1481. bool thousandSeps;
  1482. int scaleAdjust;
  1483. int adjust;
  1484. int section;
  1485. int src;
  1486. byte* dig = number.GetDigitsPointer();
  1487. char ch;
  1488. section = FindSection(format, dig[0] == 0 ? 2 : number.IsNegative ? 1 : 0);
  1489. while (true)
  1490. {
  1491. digitCount = 0;
  1492. decimalPos = -1;
  1493. firstDigit = 0x7FFFFFFF;
  1494. lastDigit = 0;
  1495. scientific = false;
  1496. thousandPos = -1;
  1497. thousandSeps = false;
  1498. scaleAdjust = 0;
  1499. src = section;
  1500. fixed (char* pFormat = &MemoryMarshal.GetReference(format))
  1501. {
  1502. while (src < format.Length && (ch = pFormat[src++]) != 0 && ch != ';')
  1503. {
  1504. switch (ch)
  1505. {
  1506. case '#':
  1507. digitCount++;
  1508. break;
  1509. case '0':
  1510. if (firstDigit == 0x7FFFFFFF)
  1511. firstDigit = digitCount;
  1512. digitCount++;
  1513. lastDigit = digitCount;
  1514. break;
  1515. case '.':
  1516. if (decimalPos < 0)
  1517. decimalPos = digitCount;
  1518. break;
  1519. case ',':
  1520. if (digitCount > 0 && decimalPos < 0)
  1521. {
  1522. if (thousandPos >= 0)
  1523. {
  1524. if (thousandPos == digitCount)
  1525. {
  1526. thousandCount++;
  1527. break;
  1528. }
  1529. thousandSeps = true;
  1530. }
  1531. thousandPos = digitCount;
  1532. thousandCount = 1;
  1533. }
  1534. break;
  1535. case '%':
  1536. scaleAdjust += 2;
  1537. break;
  1538. case '\x2030':
  1539. scaleAdjust += 3;
  1540. break;
  1541. case '\'':
  1542. case '"':
  1543. while (src < format.Length && pFormat[src] != 0 && pFormat[src++] != ch)
  1544. ;
  1545. break;
  1546. case '\\':
  1547. if (src < format.Length && pFormat[src] != 0)
  1548. src++;
  1549. break;
  1550. case 'E':
  1551. case 'e':
  1552. if ((src < format.Length && pFormat[src] == '0') ||
  1553. (src + 1 < format.Length && (pFormat[src] == '+' || pFormat[src] == '-') && pFormat[src + 1] == '0'))
  1554. {
  1555. while (++src < format.Length && pFormat[src] == '0')
  1556. ;
  1557. scientific = true;
  1558. }
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. if (decimalPos < 0)
  1564. decimalPos = digitCount;
  1565. if (thousandPos >= 0)
  1566. {
  1567. if (thousandPos == decimalPos)
  1568. scaleAdjust -= thousandCount * 3;
  1569. else
  1570. thousandSeps = true;
  1571. }
  1572. if (dig[0] != 0)
  1573. {
  1574. number.Scale += scaleAdjust;
  1575. int pos = scientific ? digitCount : number.Scale + digitCount - decimalPos;
  1576. RoundNumber(ref number, pos);
  1577. if (dig[0] == 0)
  1578. {
  1579. src = FindSection(format, 2);
  1580. if (src != section)
  1581. {
  1582. section = src;
  1583. continue;
  1584. }
  1585. }
  1586. }
  1587. else
  1588. {
  1589. if (number.Kind != NumberBufferKind.FloatingPoint)
  1590. {
  1591. // The integer types don't have a concept of -0 and decimal always format -0 as 0
  1592. number.IsNegative = false;
  1593. }
  1594. number.Scale = 0; // Decimals with scale ('0.00') should be rounded.
  1595. }
  1596. break;
  1597. }
  1598. firstDigit = firstDigit < decimalPos ? decimalPos - firstDigit : 0;
  1599. lastDigit = lastDigit > decimalPos ? decimalPos - lastDigit : 0;
  1600. if (scientific)
  1601. {
  1602. digPos = decimalPos;
  1603. adjust = 0;
  1604. }
  1605. else
  1606. {
  1607. digPos = number.Scale > decimalPos ? number.Scale : decimalPos;
  1608. adjust = number.Scale - decimalPos;
  1609. }
  1610. src = section;
  1611. // Adjust can be negative, so we make this an int instead of an unsigned int.
  1612. // Adjust represents the number of characters over the formatting e.g. format string is "0000" and you are trying to
  1613. // format 100000 (6 digits). Means adjust will be 2. On the other hand if you are trying to format 10 adjust will be
  1614. // -2 and we'll need to fixup these digits with 0 padding if we have 0 formatting as in this example.
  1615. Span<int> thousandsSepPos = stackalloc int[4];
  1616. int thousandsSepCtr = -1;
  1617. if (thousandSeps)
  1618. {
  1619. // We need to precompute this outside the number formatting loop
  1620. if (info.NumberGroupSeparator.Length > 0)
  1621. {
  1622. // We need this array to figure out where to insert the thousands separator. We would have to traverse the string
  1623. // backwards. PIC formatting always traverses forwards. These indices are precomputed to tell us where to insert
  1624. // the thousands separator so we can get away with traversing forwards. Note we only have to compute up to digPos.
  1625. // The max is not bound since you can have formatting strings of the form "000,000..", and this
  1626. // should handle that case too.
  1627. int[] groupDigits = info.numberGroupSizes;
  1628. int groupSizeIndex = 0; // Index into the groupDigits array.
  1629. int groupTotalSizeCount = 0;
  1630. int groupSizeLen = groupDigits.Length; // The length of groupDigits array.
  1631. if (groupSizeLen != 0)
  1632. groupTotalSizeCount = groupDigits[groupSizeIndex]; // The current running total of group size.
  1633. int groupSize = groupTotalSizeCount;
  1634. int totalDigits = digPos + ((adjust < 0) ? adjust : 0); // Actual number of digits in o/p
  1635. int numDigits = (firstDigit > totalDigits) ? firstDigit : totalDigits;
  1636. while (numDigits > groupTotalSizeCount)
  1637. {
  1638. if (groupSize == 0)
  1639. break;
  1640. ++thousandsSepCtr;
  1641. if (thousandsSepCtr >= thousandsSepPos.Length)
  1642. {
  1643. var newThousandsSepPos = new int[thousandsSepPos.Length * 2];
  1644. thousandsSepPos.CopyTo(newThousandsSepPos);
  1645. thousandsSepPos = newThousandsSepPos;
  1646. }
  1647. thousandsSepPos[thousandsSepCtr] = groupTotalSizeCount;
  1648. if (groupSizeIndex < groupSizeLen - 1)
  1649. {
  1650. groupSizeIndex++;
  1651. groupSize = groupDigits[groupSizeIndex];
  1652. }
  1653. groupTotalSizeCount += groupSize;
  1654. }
  1655. }
  1656. }
  1657. if (number.IsNegative && (section == 0) && (number.Scale != 0))
  1658. sb.Append(info.NegativeSign);
  1659. bool decimalWritten = false;
  1660. fixed (char* pFormat = &MemoryMarshal.GetReference(format))
  1661. {
  1662. byte* cur = dig;
  1663. while (src < format.Length && (ch = pFormat[src++]) != 0 && ch != ';')
  1664. {
  1665. if (adjust > 0)
  1666. {
  1667. switch (ch)
  1668. {
  1669. case '#':
  1670. case '0':
  1671. case '.':
  1672. while (adjust > 0)
  1673. {
  1674. // digPos will be one greater than thousandsSepPos[thousandsSepCtr] since we are at
  1675. // the character after which the groupSeparator needs to be appended.
  1676. sb.Append(*cur != 0 ? (char)(*cur++) : '0');
  1677. if (thousandSeps && digPos > 1 && thousandsSepCtr >= 0)
  1678. {
  1679. if (digPos == thousandsSepPos[thousandsSepCtr] + 1)
  1680. {
  1681. sb.Append(info.NumberGroupSeparator);
  1682. thousandsSepCtr--;
  1683. }
  1684. }
  1685. digPos--;
  1686. adjust--;
  1687. }
  1688. break;
  1689. }
  1690. }
  1691. switch (ch)
  1692. {
  1693. case '#':
  1694. case '0':
  1695. {
  1696. if (adjust < 0)
  1697. {
  1698. adjust++;
  1699. ch = digPos <= firstDigit ? '0' : '\0';
  1700. }
  1701. else
  1702. {
  1703. ch = *cur != 0 ? (char)(*cur++) : digPos > lastDigit ? '0' : '\0';
  1704. }
  1705. if (ch != 0)
  1706. {
  1707. sb.Append(ch);
  1708. if (thousandSeps && digPos > 1 && thousandsSepCtr >= 0)
  1709. {
  1710. if (digPos == thousandsSepPos[thousandsSepCtr] + 1)
  1711. {
  1712. sb.Append(info.NumberGroupSeparator);
  1713. thousandsSepCtr--;
  1714. }
  1715. }
  1716. }
  1717. digPos--;
  1718. break;
  1719. }
  1720. case '.':
  1721. {
  1722. if (digPos != 0 || decimalWritten)
  1723. {
  1724. // For compatibility, don't echo repeated decimals
  1725. break;
  1726. }
  1727. // If the format has trailing zeros or the format has a decimal and digits remain
  1728. if (lastDigit < 0 || (decimalPos < digitCount && *cur != 0))
  1729. {
  1730. sb.Append(info.NumberDecimalSeparator);
  1731. decimalWritten = true;
  1732. }
  1733. break;
  1734. }
  1735. case '\x2030':
  1736. sb.Append(info.PerMilleSymbol);
  1737. break;
  1738. case '%':
  1739. sb.Append(info.PercentSymbol);
  1740. break;
  1741. case ',':
  1742. break;
  1743. case '\'':
  1744. case '"':
  1745. while (src < format.Length && pFormat[src] != 0 && pFormat[src] != ch)
  1746. sb.Append(pFormat[src++]);
  1747. if (src < format.Length && pFormat[src] != 0)
  1748. src++;
  1749. break;
  1750. case '\\':
  1751. if (src < format.Length && pFormat[src] != 0)
  1752. sb.Append(pFormat[src++]);
  1753. break;
  1754. case 'E':
  1755. case 'e':
  1756. {
  1757. bool positiveSign = false;
  1758. int i = 0;
  1759. if (scientific)
  1760. {
  1761. if (src < format.Length && pFormat[src] == '0')
  1762. {
  1763. // Handles E0, which should format the same as E-0
  1764. i++;
  1765. }
  1766. else if (src + 1 < format.Length && pFormat[src] == '+' && pFormat[src + 1] == '0')
  1767. {
  1768. // Handles E+0
  1769. positiveSign = true;
  1770. }
  1771. else if (src + 1 < format.Length && pFormat[src] == '-' && pFormat[src + 1] == '0')
  1772. {
  1773. // Handles E-0
  1774. // Do nothing, this is just a place holder s.t. we don't break out of the loop.
  1775. }
  1776. else
  1777. {
  1778. sb.Append(ch);
  1779. break;
  1780. }
  1781. while (++src < format.Length && pFormat[src] == '0')
  1782. i++;
  1783. if (i > 10)
  1784. i = 10;
  1785. int exp = dig[0] == 0 ? 0 : number.Scale - decimalPos;
  1786. FormatExponent(ref sb, info, exp, ch, i, positiveSign);
  1787. scientific = false;
  1788. }
  1789. else
  1790. {
  1791. sb.Append(ch); // Copy E or e to output
  1792. if (src < format.Length)
  1793. {
  1794. if (pFormat[src] == '+' || pFormat[src] == '-')
  1795. sb.Append(pFormat[src++]);
  1796. while (src < format.Length && pFormat[src] == '0')
  1797. sb.Append(pFormat[src++]);
  1798. }
  1799. }
  1800. break;
  1801. }
  1802. default:
  1803. sb.Append(ch);
  1804. break;
  1805. }
  1806. }
  1807. }
  1808. if (number.IsNegative && (section == 0) && (number.Scale == 0) && (sb.Length > 0))
  1809. sb.Insert(0, info.NegativeSign);
  1810. }
  1811. private static void FormatCurrency(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info)
  1812. {
  1813. string fmt = number.IsNegative ?
  1814. s_negCurrencyFormats[info.CurrencyNegativePattern] :
  1815. s_posCurrencyFormats[info.CurrencyPositivePattern];
  1816. foreach (char ch in fmt)
  1817. {
  1818. switch (ch)
  1819. {
  1820. case '#':
  1821. FormatFixed(ref sb, ref number, nMaxDigits, info, info.currencyGroupSizes, info.CurrencyDecimalSeparator, info.CurrencyGroupSeparator);
  1822. break;
  1823. case '-':
  1824. sb.Append(info.NegativeSign);
  1825. break;
  1826. case '$':
  1827. sb.Append(info.CurrencySymbol);
  1828. break;
  1829. default:
  1830. sb.Append(ch);
  1831. break;
  1832. }
  1833. }
  1834. }
  1835. private static unsafe void FormatFixed(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info, int[] groupDigits, string sDecimal, string sGroup)
  1836. {
  1837. int digPos = number.Scale;
  1838. byte* dig = number.GetDigitsPointer();
  1839. if (digPos > 0)
  1840. {
  1841. if (groupDigits != null)
  1842. {
  1843. int groupSizeIndex = 0; // Index into the groupDigits array.
  1844. int bufferSize = digPos; // The length of the result buffer string.
  1845. int groupSize = 0; // The current group size.
  1846. // Find out the size of the string buffer for the result.
  1847. if (groupDigits.Length != 0) // You can pass in 0 length arrays
  1848. {
  1849. int groupSizeCount = groupDigits[groupSizeIndex]; // The current total of group size.
  1850. while (digPos > groupSizeCount)
  1851. {
  1852. groupSize = groupDigits[groupSizeIndex];
  1853. if (groupSize == 0)
  1854. break;
  1855. bufferSize += sGroup.Length;
  1856. if (groupSizeIndex < groupDigits.Length - 1)
  1857. groupSizeIndex++;
  1858. groupSizeCount += groupDigits[groupSizeIndex];
  1859. if (groupSizeCount < 0 || bufferSize < 0)
  1860. throw new ArgumentOutOfRangeException(); // If we overflow
  1861. }
  1862. groupSize = groupSizeCount == 0 ? 0 : groupDigits[0]; // If you passed in an array with one entry as 0, groupSizeCount == 0
  1863. }
  1864. groupSizeIndex = 0;
  1865. int digitCount = 0;
  1866. int digLength = number.DigitsCount;
  1867. int digStart = (digPos < digLength) ? digPos : digLength;
  1868. fixed (char* spanPtr = &MemoryMarshal.GetReference(sb.AppendSpan(bufferSize)))
  1869. {
  1870. char* p = spanPtr + bufferSize - 1;
  1871. for (int i = digPos - 1; i >= 0; i--)
  1872. {
  1873. *(p--) = (i < digStart) ? (char)(dig[i]) : '0';
  1874. if (groupSize > 0)
  1875. {
  1876. digitCount++;
  1877. if ((digitCount == groupSize) && (i != 0))
  1878. {
  1879. for (int j = sGroup.Length - 1; j >= 0; j--)
  1880. *(p--) = sGroup[j];
  1881. if (groupSizeIndex < groupDigits.Length - 1)
  1882. {
  1883. groupSizeIndex++;
  1884. groupSize = groupDigits[groupSizeIndex];
  1885. }
  1886. digitCount = 0;
  1887. }
  1888. }
  1889. }
  1890. Debug.Assert(p >= spanPtr - 1, "Underflow");
  1891. dig += digStart;
  1892. }
  1893. }
  1894. else
  1895. {
  1896. do
  1897. {
  1898. sb.Append(*dig != 0 ? (char)(*dig++) : '0');
  1899. }
  1900. while (--digPos > 0);
  1901. }
  1902. }
  1903. else
  1904. {
  1905. sb.Append('0');
  1906. }
  1907. if (nMaxDigits > 0)
  1908. {
  1909. sb.Append(sDecimal);
  1910. if ((digPos < 0) && (nMaxDigits > 0))
  1911. {
  1912. int zeroes = Math.Min(-digPos, nMaxDigits);
  1913. sb.Append('0', zeroes);
  1914. digPos += zeroes;
  1915. nMaxDigits -= zeroes;
  1916. }
  1917. while (nMaxDigits > 0)
  1918. {
  1919. sb.Append((*dig != 0) ? (char)(*dig++) : '0');
  1920. nMaxDigits--;
  1921. }
  1922. }
  1923. }
  1924. private static void FormatNumber(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info)
  1925. {
  1926. string fmt = number.IsNegative ?
  1927. s_negNumberFormats[info.NumberNegativePattern] :
  1928. PosNumberFormat;
  1929. foreach (char ch in fmt)
  1930. {
  1931. switch (ch)
  1932. {
  1933. case '#':
  1934. FormatFixed(ref sb, ref number, nMaxDigits, info, info.numberGroupSizes, info.NumberDecimalSeparator, info.NumberGroupSeparator);
  1935. break;
  1936. case '-':
  1937. sb.Append(info.NegativeSign);
  1938. break;
  1939. default:
  1940. sb.Append(ch);
  1941. break;
  1942. }
  1943. }
  1944. }
  1945. private static unsafe void FormatScientific(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info, char expChar)
  1946. {
  1947. byte* dig = number.GetDigitsPointer();
  1948. sb.Append((*dig != 0) ? (char)(*dig++) : '0');
  1949. if (nMaxDigits != 1) // For E0 we would like to suppress the decimal point
  1950. sb.Append(info.NumberDecimalSeparator);
  1951. while (--nMaxDigits > 0)
  1952. sb.Append((*dig != 0) ? (char)(*dig++) : '0');
  1953. int e = number.Digits[0] == 0 ? 0 : number.Scale - 1;
  1954. FormatExponent(ref sb, info, e, expChar, 3, true);
  1955. }
  1956. private static unsafe void FormatExponent(ref ValueStringBuilder sb, NumberFormatInfo info, int value, char expChar, int minDigits, bool positiveSign)
  1957. {
  1958. sb.Append(expChar);
  1959. if (value < 0)
  1960. {
  1961. sb.Append(info.NegativeSign);
  1962. value = -value;
  1963. }
  1964. else
  1965. {
  1966. if (positiveSign)
  1967. sb.Append(info.PositiveSign);
  1968. }
  1969. char* digits = stackalloc char[MaxUInt32DecDigits];
  1970. char* p = UInt32ToDecChars(digits + MaxUInt32DecDigits, (uint)value, minDigits);
  1971. int i = (int)(digits + MaxUInt32DecDigits - p);
  1972. sb.Append(p, (int)(digits + MaxUInt32DecDigits - p));
  1973. }
  1974. private static unsafe void FormatGeneral(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info, char expChar, bool bSuppressScientific)
  1975. {
  1976. int digPos = number.Scale;
  1977. bool scientific = false;
  1978. if (!bSuppressScientific)
  1979. {
  1980. // Don't switch to scientific notation
  1981. if (digPos > nMaxDigits || digPos < -3)
  1982. {
  1983. digPos = 1;
  1984. scientific = true;
  1985. }
  1986. }
  1987. byte* dig = number.GetDigitsPointer();
  1988. if (digPos > 0)
  1989. {
  1990. do
  1991. {
  1992. sb.Append((*dig != 0) ? (char)(*dig++) : '0');
  1993. } while (--digPos > 0);
  1994. }
  1995. else
  1996. {
  1997. sb.Append('0');
  1998. }
  1999. if (*dig != 0 || digPos < 0)
  2000. {
  2001. sb.Append(info.NumberDecimalSeparator);
  2002. while (digPos < 0)
  2003. {
  2004. sb.Append('0');
  2005. digPos++;
  2006. }
  2007. while (*dig != 0)
  2008. sb.Append((char)(*dig++));
  2009. }
  2010. if (scientific)
  2011. FormatExponent(ref sb, info, number.Scale - 1, expChar, 2, true);
  2012. }
  2013. private static void FormatPercent(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info)
  2014. {
  2015. string fmt = number.IsNegative ?
  2016. s_negPercentFormats[info.PercentNegativePattern] :
  2017. s_posPercentFormats[info.PercentPositivePattern];
  2018. foreach (char ch in fmt)
  2019. {
  2020. switch (ch)
  2021. {
  2022. case '#':
  2023. FormatFixed(ref sb, ref number, nMaxDigits, info, info.percentGroupSizes, info.PercentDecimalSeparator, info.PercentGroupSeparator);
  2024. break;
  2025. case '-':
  2026. sb.Append(info.NegativeSign);
  2027. break;
  2028. case '%':
  2029. sb.Append(info.PercentSymbol);
  2030. break;
  2031. default:
  2032. sb.Append(ch);
  2033. break;
  2034. }
  2035. }
  2036. }
  2037. internal static unsafe void RoundNumber(ref NumberBuffer number, int pos)
  2038. {
  2039. byte* dig = number.GetDigitsPointer();
  2040. int i = 0;
  2041. while (i < pos && dig[i] != 0)
  2042. i++;
  2043. if (i == pos && dig[i] >= '5')
  2044. {
  2045. while (i > 0 && dig[i - 1] == '9')
  2046. i--;
  2047. if (i > 0)
  2048. {
  2049. dig[i - 1]++;
  2050. }
  2051. else
  2052. {
  2053. number.Scale++;
  2054. dig[0] = (byte)('1');
  2055. i = 1;
  2056. }
  2057. }
  2058. else
  2059. {
  2060. while (i > 0 && dig[i - 1] == '0')
  2061. i--;
  2062. }
  2063. if (i == 0)
  2064. {
  2065. if (number.Kind != NumberBufferKind.FloatingPoint)
  2066. {
  2067. // The integer types don't have a concept of -0 and decimal always format -0 as 0
  2068. number.IsNegative = false;
  2069. }
  2070. number.Scale = 0; // Decimals with scale ('0.00') should be rounded.
  2071. }
  2072. dig[i] = (byte)('\0');
  2073. number.DigitsCount = i;
  2074. number.CheckConsistency();
  2075. }
  2076. private static unsafe int FindSection(ReadOnlySpan<char> format, int section)
  2077. {
  2078. int src;
  2079. char ch;
  2080. if (section == 0)
  2081. return 0;
  2082. fixed (char* pFormat = &MemoryMarshal.GetReference(format))
  2083. {
  2084. src = 0;
  2085. for (; ; )
  2086. {
  2087. if (src >= format.Length)
  2088. {
  2089. return 0;
  2090. }
  2091. switch (ch = pFormat[src++])
  2092. {
  2093. case '\'':
  2094. case '"':
  2095. while (src < format.Length && pFormat[src] != 0 && pFormat[src++] != ch)
  2096. ;
  2097. break;
  2098. case '\\':
  2099. if (src < format.Length && pFormat[src] != 0)
  2100. src++;
  2101. break;
  2102. case ';':
  2103. if (--section != 0)
  2104. break;
  2105. if (src < format.Length && pFormat[src] != 0 && pFormat[src] != ';')
  2106. return src;
  2107. goto case '\0';
  2108. case '\0':
  2109. return 0;
  2110. }
  2111. }
  2112. }
  2113. }
  2114. private static uint Low32(ulong value) => (uint)value;
  2115. private static uint High32(ulong value) => (uint)((value & 0xFFFFFFFF00000000) >> 32);
  2116. private static uint Int64DivMod1E9(ref ulong value)
  2117. {
  2118. uint rem = (uint)(value % 1000000000);
  2119. value /= 1000000000;
  2120. return rem;
  2121. }
  2122. private static ulong ExtractFractionAndBiasedExponent(double value, out int exponent)
  2123. {
  2124. ulong bits = (ulong)(BitConverter.DoubleToInt64Bits(value));
  2125. ulong fraction = (bits & 0xFFFFFFFFFFFFF);
  2126. exponent = ((int)(bits >> 52) & 0x7FF);
  2127. if (exponent != 0)
  2128. {
  2129. // For normalized value, according to https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  2130. // value = 1.fraction * 2^(exp - 1023)
  2131. // = (1 + mantissa / 2^52) * 2^(exp - 1023)
  2132. // = (2^52 + mantissa) * 2^(exp - 1023 - 52)
  2133. //
  2134. // So f = (2^52 + mantissa), e = exp - 1075;
  2135. fraction |= (1UL << 52);
  2136. exponent -= 1075;
  2137. }
  2138. else
  2139. {
  2140. // For denormalized value, according to https://en.wikipedia.org/wiki/Double-precision_floating-point_format
  2141. // value = 0.fraction * 2^(1 - 1023)
  2142. // = (mantissa / 2^52) * 2^(-1022)
  2143. // = mantissa * 2^(-1022 - 52)
  2144. // = mantissa * 2^(-1074)
  2145. // So f = mantissa, e = -1074
  2146. exponent = -1074;
  2147. }
  2148. return fraction;
  2149. }
  2150. private static uint ExtractFractionAndBiasedExponent(float value, out int exponent)
  2151. {
  2152. uint bits = (uint)(BitConverter.SingleToInt32Bits(value));
  2153. uint fraction = (bits & 0x7FFFFF);
  2154. exponent = ((int)(bits >> 23) & 0xFF);
  2155. if (exponent != 0)
  2156. {
  2157. // For normalized value, according to https://en.wikipedia.org/wiki/Single-precision_floating-point_format
  2158. // value = 1.fraction * 2^(exp - 127)
  2159. // = (1 + mantissa / 2^23) * 2^(exp - 127)
  2160. // = (2^23 + mantissa) * 2^(exp - 127 - 23)
  2161. //
  2162. // So f = (2^23 + mantissa), e = exp - 150;
  2163. fraction |= (1U << 23);
  2164. exponent -= 150;
  2165. }
  2166. else
  2167. {
  2168. // For denormalized value, according to https://en.wikipedia.org/wiki/Single-precision_floating-point_format
  2169. // value = 0.fraction * 2^(1 - 127)
  2170. // = (mantissa / 2^23) * 2^(-126)
  2171. // = mantissa * 2^(-126 - 23)
  2172. // = mantissa * 2^(-149)
  2173. // So f = mantissa, e = -149
  2174. exponent = -149;
  2175. }
  2176. return fraction;
  2177. }
  2178. }
  2179. }