MRE: https://dotnetfiddle.net/M7WeMH
I have this generic utility:
static T readValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
Reading some data from a file that should all be decimal
values, I get an exception when the text is in scientific notation e.g. "1E-5"
- this occurs rarely in the files. Testing further I find that decimal.Parse
has the same problem:
using System;
public class Program
{
static T readValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
public static void Main()
{
try
{
Console.WriteLine($"{readValue<decimal>("1E-5")}");
}
catch(Exception e)
{
Console.WriteLine(e);
}
try
{
Console.WriteLine($"{decimal.Parse("1E-5")}");
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
}
System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Number.ParseDecimal(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info) at System.Convert.ToDecimal(String value, IFormatProvider provider) at System.String.System.IConvertible.ToDecimal(IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType) at Program.readValue[T](String value)
at Program.Main()System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Number.ParseDecimal(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info) at System.Decimal.Parse(String s) at Program.Main()
This question explains how to fix it for decimal.Parse
(Parse a Number from Exponential Notation) but I this generic method is used for loading all sorts of file data from CSV files in many places... is there an equivalent fix to avoid a lot of code refactoring?