0

When I compile and run the below code, it throws the following exception:

Unhandled Exception: System.FormatException: The specified format 'X' is invalid at System.NumberFormatter.NumberToString (System.String format, System.Globalization.NumberFormatInfo nfi) [0x00000] in :0 at System.NumberFormatter.NumberToString (System.String format, Decimal value, IFormatProvider fp) [0x00000] in :0 at System.Decimal.ToString (System.String format, IFormatProvider provider) [0x00000] in :0 at System.Decimal.ToString (System.String format) [0x00000] in :0 at Program.Main ()

using System;

class Program
{
    static void Main()
    {
        decimal result = 1454787509433225637;

                    //both these lines throw a formatexception
        Console.WriteLine(result.ToString("X"));
                    Console.WriteLine(string.Format("{0:x}", result));
    }
}

Why does this happen? According to https://stackoverflow.com/a/74223/1324019 this should compile fine (and output "14307188337151A5").

Community
  • 1
  • 1
Mansfield
  • 14,445
  • 18
  • 76
  • 112
  • 1
    The other question uses the term decimal as in a base-10 number. It uses is formatting values of type `int` not `decimal`. – Anthony Dec 18 '13 at 19:17
  • 1
    In the example they are using an int variable. I think you are confusing the decimal datatype with the common terminology used when you convert decimal(integer) to hex. – Mike Schwartz Dec 18 '13 at 19:18

2 Answers2

7

Based on MSDN article for X format type you can use only Integral types only.

Result: A hexadecimal string. Supported by: Integral types only. Precision specifier: Number of digits in the result string. More information: The HexaDecimal ("X") Format Specifier.

So you need to specify int instead of decimal. Because Hex format exists only for integral values.

Sergey Litvinov
  • 7,408
  • 5
  • 46
  • 67
1

Change your code to:

int result = 1454787509433225637;
jms_g4
  • 113
  • 1
  • 7