Search code examples
csvhelper

CSV Helper Convert a scientific notation into String type


I have a phoneNumber field on a csv file that has scientific notation. I need to read the actual text and store it as string.

From other documentation I was able to convert the scientific notation to a long type using NumberStyles but I need this as a string type.

Ex: 1.11E+09 should be "1111111111" instead of 1111111111


Solution

  • I believe you would need to use ConvertUsing to get this.

    public class Program
    {
        static void Main(string[] args)
        {
            using (var stream = new MemoryStream())
            using (var writer = new StreamWriter(stream))
            using (var reader = new StreamReader(stream))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            using(var csvWriter = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
            {
                writer.WriteLine("Id,PhoneNumber");
                writer.WriteLine("1,1.11E+09");
                writer.Flush();
                stream.Position = 0;
    
                csv.Configuration.RegisterClassMap<TestMap>();
    
                var records = csv.GetRecords<Test>().ToList();
            }
        }
    }
    
    public class Test
    {
        public int Id { get; set; }
        public string PhoneNumber { get; set; }
    }
    
    public sealed class TestMap : ClassMap<Test>
    {
        public TestMap()
        {
            AutoMap(CultureInfo.InvariantCulture);
            Map(m => m.PhoneNumber).ConvertUsing(row => decimal.Parse(row.GetField<string>("PhoneNumber"), NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint).ToString());
        }
    }