问题
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").
回答1:
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.
回答2:
Change your code to:
int result = 1454787509433225637;
来源:https://stackoverflow.com/questions/20666474/why-does-converting-between-decimal-and-hex-throw-a-formatexception