Csvhelper: Int32 Conversion from Float

Created on 28 Nov 2017  路  8Comments  路  Source: JoshClose/CsvHelper

Is it possible to have type conversions be actual Convert.toIn32 so as to get the int value and ignore the decimal places?

Most helpful comment

Convert will not work when doing Convert.ToInt32("1.0"). It fails just like TryParse does.

Here are a couple options for you. You can create a custom type converter that will get the value as a float first, then change to an int. You can convert int a mapping directly.

Map(m => m.MyIntProperty).ConvertUsing(row => (int)row.GetField<float>("MyIntProperty"));

All 8 comments

Do you have a CSV field of 123.456 and you want it to be set to an int property?

Exactly.
This should result in 123 ignoring the floating point

How can you do that using Convert.ToInt32( "123.456" )?

`using System;

public class Program
{
public static void Main()
{
Decimal number=1.23M;

    int convertedValue=Convert.ToInt32(number);


    Console.WriteLine(convertedValue);
}

}`

output:1
https://dotnetfiddle.net/5KZPbW

You already have a decimal though. In a CSV file, that field is a string so you need to convert from a string of 1.23 to an int.

I don't quite follow . can you show a sample code of how that is done?
anyway this is my scenario:
1.data from my db gets exported to excel
2.Due to whatever reason excel appends a .0-to the integer fields

  1. that data gets exported to csv as float/double/decimal (all represented as strings as you mentions)
    4.then there's "parsing" to bind the data as its object by csv helper
  2. this parse i think could be convert so instead of throwing an error upon failure, it will instead assign a default as convert does
    the parse code which could be looked at:
    if( int.TryParse( text, numberStyle, memberMapData.TypeConverterOptions.CultureInfo, out i ) ) { return i; }

Convert will not work when doing Convert.ToInt32("1.0"). It fails just like TryParse does.

Here are a couple options for you. You can create a custom type converter that will get the value as a float first, then change to an int. You can convert int a mapping directly.

Map(m => m.MyIntProperty).ConvertUsing(row => (int)row.GetField<float>("MyIntProperty"));

Instead of seeing that exception here is how i do it:
Map(m => m.Grupo).ConvertUsing(row => { return byte.TryParse(row.GetField("grupo"), out byte v) ? (byte?)v : null; });

Was this page helpful?
0 / 5 - 0 ratings