Home > Software engineering >  Converting float to int32 when parsing csv using tiny csv helper
Converting float to int32 when parsing csv using tiny csv helper

Time:10-05

I wonder is it possible to convert float to int32 automatically when parsing csv using tiny csv helper? Datetime is easily converted using the code below:

MapProperty(0, x => x.Date, new DateTimeConverter("yyyyMMdd"));

but other columns in csv are in format 123456.00 and it raises error when I map to an int property. Can anyone give an example on how to achieve this? Thanks

CodePudding user response:

So, one solution to this is to define your own ITypeConverter as follows :

using TinyCsvParser.TypeConverter;
using System;

public class CustomIntConverter : ITypeConverter<int>{ 

    public bool TryConvert(string value, out int result)
    {
       try { 
            float floatValue = float.Parse(value); 
            int intValue = (int)floatValue; 
            result = intValue;
            return true; 
        } catch {
            result = default(int);
            return false;
        }

    }

    public Type TargetType { get => typeof(int); } 


}

and use it like this :

MapProperty(0, x => x.YourIntField, new CustomIntConverter());
  • Related