c# - Why does NumberStyles.AllowThousands work for int.Parse but not for double.Parse in this example? -


to parse string representing number comma separating thousand digits rest, tried

int tmp1 = int.parse("1,234", numberstyles.allowthousands); double tmp2 = double.parse("1,000.01", numberstyles.allowthousands); 

the first statement can run, while second fails notification

an unhandled exception of type 'system.formatexception' occurred in mscorlib.dll

additional information: input string not in correct format.

why both not succeed? thanks.

you should pass allowdecimalpoint, float, or number style (latter 2 styles combination of several number styles include allowdecimalpoint flag):

double.parse("1,000.01", numberstyles.allowthousands | numberstyles.allowdecimalpoint) 

when provide number style parsing method, specify exact style of elements can present in string. styles not included considered not allowed. default combination of flags (when don't specify style explicitly) parsing double value numberstyles.float , numberstyles.allowthousands flags.

consider first example parsing integer - haven't passed allowleadingsign flag. following code throw exception:

int.parse("-1,234", numberstyles.allowthousands) 

for such numbers, allowleadingsign flag should added:

int.parse("-1,234", numberstyles.allowthousands | numberstyles.allowleadingsign) 

Comments