Skip to content

Add the ability to parse/format a float/double from/to a hexadecimal literal #1630

@dovisutu

Description

@dovisutu

Part of #27204

In IEEE 754:2008 part 5.12.3, transfering a float/double from/to an external hexadecimal-significand character sequence representing finite number is requested while we don't have it yet. The pattern is like this: (regex)

[+-]?0[xX](?:[\da-fA-F]*\.[\da-fA-F]+|[\da-fA-F]\.?)(?:[pP][+-]?\d+)?

notice that this is slightly different to the standard based on the discussion below, which talked about the exponent part

which means:

valid invalid
+0x7ff.3edp+1 +7ff.3edp-1
0x7ff.3edp+1 0x7ff.3ede+1
0x7ff.3edp1 0x7ff.3uup1
+0x7ff.3edp1 0x7ff.3ed
+0X7FF.3EDP1 0X7FF.3ED
-0x7ff.3edp1 0x7ff_3edp-1
0x7ff. +-0x7ff.3edp-1
0x7ff 0x7fu.3edp-1
0x.3edp-1 0x.p-1

benefits

  • Easier parsing for native hexadecimal float/double. for example, 0x0.ffp0 is the equivalent of 0.99609375 while using less chars. Same for formatting as it reduces the size of string to transfer.
  • Parsed number is percise in the limit of float/double's limitations. Since both float and double are based on raw bit, transistion from hexadecimal literal to them would be easier and without rounding if they are in the limitation. parsing decimals, on the other hand, would often has to round.
  • It's in IEEE 754:2008/2019 standard, so it's necessary to add it.

proposal APIs

namespace System.Globalization {
    [Flags]
    enum NumberStyles {
        // ...,
        HexFloat = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowHexSpecifier | AllowDecimalPoint
        // ,...
    }
}

And let Numbers.ParseDouble/Single(string s, NumberStyles style[, NumberFormatInfo info]) accept Numberstyles.HexFloat (or it without NumberStyles.AllowDecimalPoint) and correctly parse string.

Edit Numbers.FormatDouble/Single(ref ValueStringBuilder sb, double/float value, ReadOnlySpan<char> format, NumberFormatInfo info) so that they can correctly identify X specifier (which is also used for outputting integers in hex) which may have a trailing precision specifier, and correctly format it.

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Numericshelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions