.net - C# float max parse error -
i declared byte array contains 4 bytes.
byte[] bts = new byte[] { 0xff, 0xff, 0x7f, 0x7f }; float f1 = bitconverter.tosingle(bts, 0); string s = f1.tostring(); float f2 = float.parse(s); byte[] bts2 = bitconverter.getbytes(f2);
after conversion, realized output changes
{ 0xff, 0xff, 0x7f, 0x7f }
to
{ 0xfd, 0xff, 0x7f, 0x7f }
why did happen?
if @ f1
, f1.tostring()
in watch window see that
f1
= 3.40282347e+38
f1.tostring()
= 3.402823e+38
which means tostring
method outputs string
representing trimmed number , not accurate 4 byte float
, but why?
the default float.tostring
uses the g
specifier in standard numeric format strings
has 7 digit accuracy floats
.
you can use other overload of tostring
specify format specifier , provide amount of digits want represent:
string s = f1.tostring("g10");
a better way use "r"
specifier lossless
string s = f1.tostring("r");
msdn: round-trip ("r") format specifier used ensure numeric value converted string parsed same numeric value.
Comments
Post a Comment