runtime: Double.TryParse fails on string that has thousands separator. Regression?
Description
I format a double value to string and parsing that string back to a double fails, using the same culture info.
Reproduction Steps
This test fails for me
var value = 2000.0;
var valueAsText = value.ToString("N5", CultureInfo.CurrentCulture); // 2,000.00000
var success = double.TryParse(valueAsText, NumberStyles.Any, CultureInfo.CurrentCulture, out value);
Assert.True(success);
You can find it here in this repo: https://github.com/katjoek/DoubleTryParseFails
Expected behavior
I expect it to be possible to convert a double value to a string and back again when using the same culture info and allowing any kind of formatting style when parsing.
Actual behavior
double.TryParse(“2,000.00000”, NumberStyles.Any, CultureInfo.CurrentCulture, out var value) returns false eventhough that string was created just before using 2000.0.ToString(“N5”, CultureInfo.CurrentCulture)
Regression?
I think not. I also reproduces on dotnet 6.0.
Known Workarounds
Format the string in a different way: do not have the thousands separator. In my project, using format “N5” fails, using “F5” works.
Configuration
This is with .NET core 8.0 on Windows 10
Processor 11th Gen Intel® Core™ i7-11800H @ 2.30GHz 2.30 GHz Installed RAM 32.0 GB (31.7 GB usable) Product ID 00330-80000-00000-AA459 System type 64-bit operating system, x64-based processor Pen and touch No pen or touch input is available for this display
Edition Windows 10 Enterprise Version 22H2 Installed on 17/08/2022 OS build 19045.4170 Experience Windows Feature Experience Pack 1000.19054.1000.0
My regional settings:
Other information
No response
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 15 (9 by maintainers)
As an addition to @tannergooding 's question, because CSV is meant to be an interchange format it should be read/written with the invariant culture (and relying on a machine’s culture is doomed to failure). And also without the thousands separator, especially if the separator would be the field delimiter.
If you know it is invariant, then why not just use
double.Parse(..., CultureInfo.InvariantCulture)?