Rounding Numbers

Apr 13, 2010 at 4:30 PM

When I view my .xls file in Excel, the numeric values of my cells are rounded to the nearest whole number (ie 35).  But when I use the Excel Data Reader to read the file, the values have the decimal places (ie. 34.666666667).  I assume this is a formatting issue?  Is there any way to have the Excel Data Reader values match what would be should within Excel?

I'm using excelReader.GetString(i) and excelReader.GetValue(i)


Apr 22, 2010 at 10:50 PM

The DataReader is reading the raw data, without any special formatting applied by the Excel client itself.  As such, the Excel file is truly storing the number 34.666...., with the rounding being purely cosmetic.

Your best approach is to read the data, then apply your own rounding logic to the value after converting.

decimal tempDecimal;
var decimalString = excelReader.GetString(i);

if ( decimal.TryParse( decimalString, out tempDecimal ) )
     var myDecimal = Math.Round( tempDecimal );
     // do something with your decimal;
     throw new InvalidOperationException("Input string was not in the correct format.");